当var
被标记为可选的Swift包裹它时,当需要实际值时,将执行展开。
var anOptional : String? = "wrapping"
print("\(anOptional!) unwrapping")
在包装和展开可选项时实际发生了什么?
答案 0 :(得分:4)
“可选”是包含两种可能情况的枚举,.None
和.Some
。 .Some
大小写具有关联值,即包装值。 To"打开"可选是返回该关联值。就好像你这样做了:
let anOptional : String? = "wrapping"
switch anOptional {
case .Some(let theString):
println(theString) // wrapping
case .None:
println("it's nil")
}
答案 1 :(得分:1)
可选是简单变量和其他变量一样,但事情是它可能有两个值,可选变量中的值可能是nil
或“某个值”。例如:
var anOptional : String?
println(anOptional) //nil
println(anOptional!) //error as optional has no value and we are trying to wrap it and getting the value
anOptional = "it has some value";
println(anOptional!) //"it has some value" as it has value and we are wrapping it
以下是解包过程http://appventure.me/2014/06/13/swift-optionals-made-simple/
的链接