Swift: static string evaluated empty

Viewed 304

I looked for this on SO and unfortunately there's no answer.

I have this declared:

struct ChatRoomsLite {
    public static let CHAT_ROOM_LITE_BASE = "ChatRoomsLite"
    public static let TIME_OF_LAST_MESSAGE = "timeLastMessage"
    public static let NUM_OF_UNREAD_MSGS = "unreadMessages"
    public static let LAST_MESSAGE = "lastMessage"
    public static let CONTACT_ID = "contactB_Id"
    public static let CONTACT_NAME = "contactName"
}

And for some reason, one of the constants is being evaluated EMPTY!

enter image description here

As you can see, the CONTACT_NAME is evaluated empty even though it's defined as public static let

How can this be fixed ?

1 Answers

As The Swift Programming Language Guide says:

Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.

So your constant is not empty, it simple hasn't been instantiated at that moment because you've never accessed it before.

Such behavior can not lead to any problem. Here is an example:

struct MyStruct {
    public static let ID = "Identifier"
}

//_ = MyStruct.ID

print(MyStruct.ID)

If you run this code and add a breakpoint at print line, you will also see that MyStruct.ID is empty, but correct value will be printed at the console, because constant was instantiated after first access.

If you uncomment the commented line and repeat the same thing, MyStruct.ID won't be empty at print line breakpoint, because it was already instantiated when you accessed it in a previous line.

Related