What happens while wrapping and unwrapping an optional in Swift?

﹥>﹥吖頭↗ 提交于 2019-12-08 10:28:22

问题


When a var is marked as an optional Swift wraps it and when actual value is needed unwrapping is performed.

var anOptional : String? = "wrapping"
print("\(anOptional!)  unwrapping")

What actually happens during wrapping and unwrapping of an optional?


回答1:


An Optional is an enum with two possible cases, .None and .Some. The .Some case has an associated value which is the wrapped value. To "unwrap" the optional is to return that associated value. It is as if you did this:

let anOptional : String? = "wrapping"
switch anOptional {
case .Some(let theString):
    println(theString) // wrapping
case .None:
    println("it's nil")
}



回答2:


Optional is simple variable as others but the thing is it may have two values either the value in optional variable may be nil or "some value". For Example:

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

Here is the link for unwrapping process http://appventure.me/2014/06/13/swift-optionals-made-simple/



来源:https://stackoverflow.com/questions/27370700/what-happens-while-wrapping-and-unwrapping-an-optional-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!