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)"
}