Swift Optionals

option-type, swift

Solution

Swift requires types that can be optional to be explicitly declared, so the first snippet is an example of creating a nullable string:

var optionalString: String? = "Hello"
optionalString = nil

In order to make use of a nullable string it needs to realized which it does with the `!` suffix so to convert a `String?` into a `String` you can do:

var name : String = optionalName!

But Swift also provides a shorthand of checking for and realizing a nullable inside a conditional block, e.g:

if let name = optionalName {
    greeting = "Hello, \(name)"
}

Which is the same as:

if optionalName != nil {
    let name = optionalName!
    greeting = "Hello, \(name)"
}

Problem

Can someone please explain me the following code (appears on page 11 of Apple's Swift book): ``` var optionalString: String? = "Hello" optionalString = nil var optionalName: String? = "Einav Sitton" var greeting = "HELLO!" if let name = optionalName { greeting = "Hello, \(name)" } ```

Original source

Related problems