[英]Can a non-optional type be nil?
In a MessagesViewController,
we are using the overridden delegate methods.在
MessagesViewController,
我们使用覆盖的委托方法。 When sending a message, didStartSending
is called as expected.发送消息时,会按预期调用
didStartSending
。 The non-optional parameter message
is nil though:尽管非可选参数
message
为零:
override func didStartSending(_ message: MSMessage, conversation: MSConversation) {
if message != nil {
logInfo("didStartSending message: \(message) conversation: \(conversation)")
} else {
logInfo("didStartSending message: \("why nil") conversation: \(conversation)")
}
}
Log:日志:
"didStartSending message: why nil conversation: <MSConversation: 0x17026ca00>"
Debugging with po:使用 po 进行调试:
(lldb) po message
<uninitialized>
Also we get the expected warning on the if
line:我们也在
if
行得到预期的警告:
Comparing non-optional value of type MSMessage to nil always returns true
The same is true for didCancelSending
. didCancelSending
也是如此。
How can a non-optional, which can not be nil by definition in my understanding, actually be nil.在我的理解中,根据定义不能为零的非可选,实际上如何为零。
The compiler will try hard to make it impossible that a non-optional value is ever nil.编译器将努力使非可选值永远为零。 I think you can get past the compiler by declaring an Objective-C function as nonnull and then making it return nil.
我认为您可以通过将 Objective-C 函数声明为非空函数然后使其返回 nil 来绕过编译器。 If you do that, then all odds are off.
如果你这样做,那么所有的可能性都没有了。 Anything can happen.
任何事情都可能发生。
I haven't tried if comparing a non-optional with nil is legal or not;我还没有尝试过将非可选与 nil 进行比较是否合法; if it is legal then the compiler is allowed to assume that the comparison will always return "false";
如果合法,则允许编译器假定比较将始终返回“false”; so checking that a non-optional that should never be allowed to be nil is actually nil or not will not work.
所以检查一个不应该被允许为零的非可选实际上是否为零是行不通的。
I see you checked it... So comparing non-optional and nil is legal, but the compiler assumes they will never be the same and warns you.我看到你检查了它......所以比较 non-optional 和 nil 是合法的,但编译器假设它们永远不会相同并警告你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.