1

I'm reading Apple's developer documentation on Optional Binding

Why can't I use:

if someOptional? {

statements

}

Instead of

if let constantName = someOptional {

statements

}

Why when there is no need for a local variable or constant?

Community
  • 1
  • 1
Nutela
  • 85
  • 7
  • 1
    you use optional binding when you want value from the optional...not just check if the optional value contains value or nil – LC 웃 May 02 '16 at 18:38
  • 2
    you can always do `if someOptional != nil {` or if you don't need the unwrapped value you can also do `if let _ = someOptional {` – Ozgur Vatansever May 02 '16 at 18:38

2 Answers2

5

Why can't I use: if someOptional? {...}

Because the ? suffix on an optional variable is reserved for optional chaining, which allows you to access a property or call a method on a given optional variable. For example:

// returns an optional version of a given property
let aProperty = anOptional?.someProperty

// calls the method if aProperty contains a value – otherwise doesn't
aProperty?.doSomething()

If you just want to check whether an optional contains a value, but don't care about that underlying value, you can simply compare it with nil. For example:

if anOptional != nil {
    // do something
}
Hamish
  • 78,605
  • 19
  • 187
  • 280
  • If you're interested, I co-wrote [an answer here](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) that lists (almost) all the ways of safely working with optionals – although the Apple Swift docs are hard to beat! – Hamish May 02 '16 at 19:28
1

The simple answer is that someOptional is an Optional, whereas constantName is a Type.

An Optional is not simply the state of a variable, it's an entirely different type. If you were to set var someOptional: String? to var someOptional: String, you're not unwrapping someOptional, you're actually changing the type of someOptional.

It's functionally the same as changing var someOptional: String to var someOptional: Int

GetSwifty
  • 7,568
  • 1
  • 29
  • 46