What happens while wrapping and unwrapping an optional in Swift?

373 Views Asked by At

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?

2

There are 2 best solutions below

4
On BEST ANSWER

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
On

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/