4

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)"
}
YogevSitton
  • 10,068
  • 11
  • 62
  • 95

2 Answers2

8

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)"
}
mythz
  • 141,670
  • 29
  • 246
  • 390
1

Are you talking about this line?

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

In english, this says: If optionalName has a value, set that value to the temporary variable name and then use it to construct a new string. If optionalName is nil do nothing at all.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337