Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Optionals [duplicate]

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)"
}
like image 575
YogevSitton Avatar asked Sep 15 '25 10:09

YogevSitton


1 Answers

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)"
}
like image 99
mythz Avatar answered Sep 17 '25 04:09

mythz