0

I'm currently going through the Swift guided tour playground that can be found on apple's website. I have some knowledge of C and C# but am mostly working with javascript everyday.

I stumbled upon these lines on the playground:

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
   greeting = "Hello, \(name)"
}

In this case, the "greeting" variable would be "Hello, John Appleseed", or simply "Hello!" if I was to set optionalName to nil.

The documentation states:

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

What i'm wondering is, how does that differ from my usual way of doing things which would be:

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if optionalName {
   greeting = "Hello, \(optionalName)"
}

Because the result is actually the same on the playground, I'd like to understand what the difference is, and why I should use on over the other.

Thanks !

Guillaume M
  • 257
  • 3
  • 9
  • possible duplicate of [Use of an optional value in Swift](http://stackoverflow.com/questions/24030053/use-of-an-optional-value-in-swift) – jrturton Jul 18 '14 at 17:49

1 Answers1

1

name is a String but optionalName is a String?.

It doesn't matter for string formatting because that example will accept any type.

Where type is important, however, your second example will fail.

For example, this won't work:

var optionalName: String? = "John Appleseed"
var names :[String] = []

if optionalName {
    names += name
}

(You can't add a String? to an array of Strings.)

You can replace it with the if let syntax:

if let name = optionalName {
    names += name
}

Or you could replace it with the unwrap operator:

if optionalName {
    names += optionalName!
}

In your original example, if you wanted to avoid if let, the more correct usage would be to add the unwrap operator:

if optionalName {
   greeting = "Hello, \(optionalName!)"
}
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • Alright i get it, I guess what confused me is the fact that the provided exemple didn't actually show a necessary case but just a possible one. Thanks a lot for the clear answer ! – Guillaume M Jul 18 '14 at 17:37
  • Also since optionals are by default set to nil in Swift the if let syntax helps protect values from getting excited when they are nil but also lets you change name to equal optionalName if it isn't nil. Check out the optional Chaining for more https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html#//apple_ref/doc/uid/TP40014097-CH21-XID_311 – domshyra Jul 18 '14 at 22:11