问题
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