gpt4 book ai didi

Swift:静态字符串评估为空

转载 作者:搜寻专家 更新时间:2023-10-31 22:38:27 24 4
gpt4 key购买 nike

我在 SO 上寻找这个,不幸的是没有答案。

我已经声明了:

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"
}

并且出于某种原因,其中一个常量被评估为 EMPTY!

enter image description here

如您所见,CONTACT_NAME 被评估为空,即使它被定义为 public static let

如何解决这个问题?

最佳答案

作为The Swift Programming Language Guide说:

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.

所以你的常量不是空的,它很简单,在那一刻还没有被实例化,因为你以前从未访问过它。

这样的行为不会导致任何问题。这是一个例子:

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

//_ = MyStruct.ID

print(MyStruct.ID)

如果您运行此代码并在 print 行添加断点,您还会看到 MyStruct.ID 为空,但控制台会打印出正确的值,因为常量是第一次访问后实例化的。

如果您取消注释注释行并重复相同的操作,MyStruct.ID 将不会在 print 行断点处为空,因为它在您访问时已经实例化它在前一行。

关于Swift:静态字符串评估为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52217686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com