3

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

3
  • "Since Swift can't access compile variables" Well, that's not really true, is it? It depends what you want to do. You can set an environment variable in the scheme and access its value using NSProcessInfo. And Swift has an #if/#else/#endif construct that tests whether something is defined. Commented Apr 13, 2015 at 18:51
  • If you need a fast solution, just use an empty string instead. Commented Apr 13, 2015 at 18:53
  • @matt Should have been more clear, My compile variables are stored as "Other C Flags" under build settings, and correct me if I'm wrong, but I believe NSProcessInfo cannot access them. I don't want to move them to scheme setting so I ended up setting the value to an empty string in my if/else macro per Sulthan suggestion Commented Apr 13, 2015 at 20:01

1 Answer 1

1

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 } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.