swiftoption-typeforced-unwrapping

Difference between optional and forced unwrapping


Below is the code for optional string for variable name yourname and yourname2.

Practically what is difference between them and how forced unwrapping in case of yourname2

var yourname:String?
yourname = "Paula"
if yourname != nil {
    println("Your name is \(yourname)")
}

var yourname2:String!
yourname2 = "John"
if yourname2 != nil {
    println("Your name is \(yourname2!)")
}

Solution

  • The String? is normal optional. It can contain either String or nil.

    The String! is an implicitly unwrapped optional where you indicate that it will always have a value - after it is initialized.

    yourname in your case is an optional, yourname2! isn't. Your first print statement will output something like "Your name is Optional("Paula")"

    Your second print statement will output something like "Your name is John". It will print the same if you remove the exclamation mark from the statement.

    By the way, Swift documentation is available as "The Swift Programming Language" for free on iBooks and the very latest is also online here.