[英]Swift nil values behaviour
Can you send messages to nil
in Swift
the same way you can in Objective-C
without causing a crash? 您可以像在
Objective-C
一样在Swift
中将消息发送到nil
而不导致崩溃吗?
I tried looking into the documentation and couldn't find anything relating to this. 我尝试查看文档,但找不到与此相关的任何内容。
Not exactly, you have to use Optional Chaining . 不完全是,您必须使用Optional Chaining 。 In swift, an instance can only be
nil
if it is declared as an "optional" type. 快速地,实例被声明为“可选”类型时只能为
nil
。 Normally this looks like this: 通常情况如下:
var optionalString : String?
Notice the ?
注意
?
after the String
That is what makes it possible to be nil 在
String
这就是可能变为零的原因
You cannot call a method on that variable unless you first "unwrap" it, unless you use the aforementioned Optional Chaining. 除非您先“解包”它,否则您不能在该变量上调用方法,除非您使用上述的“可选链接”。
With optional chaining you can call multiple methods deep, that all allow for a nil value to be returned: 通过可选的链接,您可以深度调用多个方法,所有方法都允许返回nil值:
var optionalResult = optionalString.method1()?.method2()?.method3()
optionalResult
can also be nil. optionalResult
也可以为nil。 If any of the methods in the chain return nil, methods after it are not called, instead optionalResult immediately gets set to nil. 如果链中的任何方法返回nil,则不调用其后的方法,而是将optionalResult立即设置为nil。
You cannot deal directly with an optional value until you explicitly handle the case that it is nil. 您不能直接处理可选值,除非您明确处理它为nil的情况。 You can do that in one of two ways:
您可以通过以下两种方式之一进行操作:
println(optionalString!)
This will throw a runtime error if it is nil, so you should be very sure that it is not nil 如果它为nil,这将引发运行时错误,因此您应该确保它不是nil。
You can do this by using a simple if statement: 您可以使用简单的if语句来做到这一点:
if optionalString {
println(optionalString!)
}
else {
// it was nil
}
or you can assign it to a scoped variable so that you don't have to forcefully unwrap it: 或者您可以将其分配给作用域变量,这样就不必强行解开包装:
if let nonoptionalString = optionalString {
println(nonoptionalString)
}
else {
// it was nil
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.