我在Swift
中有一个功能,]
func getValue(param: String!) -> String {
//access param
//return a string
}
通话就像,
let retVal = getValue(param: nil)
我预计参数将在考虑功能参数的同时尝试强制展开并崩溃。但是代码没有崩溃。谁能让我知道我想念什么?
签名时会有什么不同,
func getValue(param: String?) -> String
这里!
表示参数将保存字符串值或nil
。因此,当您将nil
分配给!
时,它不应该崩溃。但是,当您尝试访问该值时,它将崩溃。
您对代码的此修改将导致崩溃,因为我们试图访问变量nil
中的值。
func getValue(param: String!) -> String {
if param.isEmpty {
return ""
}
return ""
}
let retVal = getValue(param: nil)
另一个例子:
var string: String!
string = nil //This will not crash, but after this line if you try to access or perform any operation on it, it will
现在有关此func getValue(param: String?)
:
在这种情况下,与上述情况不同,param
将为optional type
。因此,在这里您必须将其拆开。
简单地解包的可选(或IUO)可能仍包含nil
作为值!如果使用IUO,则仅当您在其上调用任何方法/变量(例如param.count
)或将其分配给NON-Optional变量时才会崩溃,该变量将导致强制展开操作:
var param: String! = nil
var nonOptionalStr: String = param //<- Crash because it will try to force-unwrap param
另一个崩溃示例:
func foo(param: String!) -> String {
return param //<- Crash! As return type is non-optional String it will try to force unwrap the param.
}
另一方面 IUO(以及Optionals)的类型也为Any
,因此,如果将包含nil的String!
传递给期望Any
的方法,则它不会崩溃,因为会有不能轻松地将Any?
强制展开为Any
。
let str: String! = nil
print(str) //<- No Crash! Becaise print accepts Any, so there will be no force-unwrapping
//Output: nil
另一个类型为Any
的示例:
var a: Any? = nil
var b: Any = a //<- No Crash! As (Any?) is kind of (Any), though you will get a warning from compiler: Expression implicitly coerced from 'Any?' to 'Any'
print(b)
//Output: nil