Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 1.2 optional external variable?

Tags:

ios

swift

Since Swift can't access compile variables, I created an objective c extern variable that points to the compile variable.

CompileVaribleConvertor.h

extern NSString * const NetworkApiBasicAuthUsername;

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

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. Binary operator '!=' cannot be applied to operands of type 'String' and 'nil'

How do I make the extern variable an optional, I tried defining the extern variable as __nullable with no luck

like image 237
aryaxt Avatar asked Dec 07 '25 07:12

aryaxt


1 Answers

I just did some fast testing and I am pretty sure it's a bug. There is no way to force global variables (or constants) to be optionals. Even if they are initialized with a nil. That can't be correct.

Macros are not connected with the 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
}
like image 118
Sulthan Avatar answered Dec 08 '25 21:12

Sulthan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!