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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With