简体   繁体   English

Swift 1.2可选外部变量?

[英]Swift 1.2 optional external variable?

Since Swift can't access compile variables, I created an objective c extern variable that points to the compile variable. 由于Swift无法访问编译变量,因此我创建了一个指向编译变量的目标c extern变量。

CompileVaribleConvertor.h CompileVaribleConvertor.h

extern NSString * const NetworkApiBasicAuthUsername;

CompileVaribleConvertor.m CompileVaribleConvertor.m

// AUTH_USERNAME might not be defined depending on the environment we are pointing to
#if defined(AUTH_USERNAME)
    NSString * const NetworkApiBasicAuthUsername = @AUTH_USERNAME;
#else
    NSString * const NetworkApiBasicAuthUsername = nil;
#endif

NetworkManager.swift NetworkManager.swift

if CSNetworkApiAuthUsername != nil {
  // Basic auth is required set them
}

This code used to work on Swift 1.0 , but Swift 1.2 gives compile error. 这段代码用于Swift 1.0 ,但Swift 1.2给出了编译错误。 Binary operator '!=' cannot be applied to operands of type 'String' and 'nil' 二进制运算符'!='不能应用于'String'和'nil'类型的操作数

How do I make the extern variable an optional, I tried defining the extern variable as __nullable with no luck 如何使extern变量成为可选项,我尝试将extern变量定义为__nullable而没有运气

I just did some fast testing and I am pretty sure it's a bug. 我刚做了一些快速测试,我很确定这是一个bug。 There is no way to force global variables (or constants) to be optionals. 没有办法强制全局变量(或常量)成为可选项。 Even if they are initialized with a nil . 即使它们被初始化nil That can't be correct. 这不可能是正确的。

Macros are not connected with the bug. 宏与bug无关。 As a workaround, you can use a function instead of a constant: 作为解决方法,您可以使用函数而不是常量:

NSString* NetworkApiBasicAuthUsername() {
#if defined(AUTH_USERNAME)
    return @AUTH_USERNAME;
#else
    return nil;
#endif
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM