-1
var optionalname: String? = "QUAN"

let name1 = optionalname

var greeting1 = "Hello, \(name1)"

print(greeting1)

if let name2 = optionalname {
    var greeting2 = "Hello, \(name2)"
    print(greeting2)
}

print(greeting1) gives:

"Hello, Optional("QUAN")\n"

print(greeting2) gives:

"Hello, QUAN\n"

Can someone helps me explain the reasons behind the difference ? Thanks!

Quan Vuong
  • 1,919
  • 3
  • 14
  • 24
  • 3
    Lookup "optional binding" in the Swift reference. – Martin R Nov 06 '16 at 18:45
  • Related: http://stackoverflow.com/questions/29717210/when-should-i-compare-an-optional-value-to-nil, http://stackoverflow.com/questions/33769366/why-use-optional-binding, – Martin R Nov 06 '16 at 18:50

1 Answers1

0

If your value is an optional(?) it means that there does not have to be a value (It can be empty and there is no error). If you have empty non-optional value your code will fail. There is an article from apple about this: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

This is what apple says about optionals:

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil.

0ndre_
  • 3,577
  • 6
  • 26
  • 44