3

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
  • 9,908
  • 11
  • 59
  • 93
  • take a look here: http://stackoverflow.com/questions/24030053/use-of-an-optional-value-in-swift/24030107#24030107 – Connor Jun 04 '14 at 19:49

2 Answers2

7

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
  • 138,929
  • 27
  • 237
  • 382
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
  • 162,909
  • 46
  • 287
  • 312