0

Optional binding is a method to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

var possibleNumber: Int? = 123

if let actualNumber = Int(possibleNumber){
    print("\"possibleNumber\" has an integer value of \(actualNumber)")
} else {
    print("\"possibleNumber\" could not be converted to an integer")
}

Question Does the Binding mean the action of assigning the valid value into the temporary constant/variable? I.e. "binding" those two things together?

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
SLN
  • 4,772
  • 2
  • 38
  • 79

3 Answers3

2

Does the Binding mean the action of assigning the valid value into the temporary constant/variable? I.e. "binding" those two things together?

Yes. Basically, assignment of a value to a variable name is a binding — it "binds" the name to the value. So even this is a binding:

let x = 1

What's special with if let is that the binding takes place only if the value is an Optional that can be safely unwrapped (that is, it is not nil). If it can't be unwrapped safely, it is not unwrapped and no binding takes place (and the if condition fails).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • good to know that "binding" is not only for the Optional, definition is also a binding. Thanks a lot for your explanation – SLN Jun 14 '16 at 20:55
  • This is more than just binding, it's also memory allocation (on stack) and initialization ;) – Alexander Aug 05 '16 at 18:24
  • @matt OMG how stupid I am! I've asked this question before. I need a quiet introspection. – SLN Aug 05 '16 at 18:41
  • @AlexanderMomchliov in case the OP deletes his question, why not move your answer over here? That way it can live on, including your point about "more than just binding". – matt Aug 05 '16 at 19:18
  • On mobile right now, I'll do that shortly. Is there a way to view your answers to deleted questions? – Alexander Aug 05 '16 at 19:22
1

When you associate existing data/code a new identifier (name) by which to refer to it, you're "binding" it to that identifier.

There's also "conditional binding", such as when you use if let. It binds the contents of the optional only if there's something there... conditionally.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • And to add to my answer: keep in my that variable identifiers only exist for us as programmers of a high level programming language. The moment that code's compiled, they're stripped away, and data is just referred to directly by its memory address. As such, optional binding probably doesn't even change the compiled code output. It just exists to validate type safety – Alexander Aug 05 '16 at 19:34
0

We use optional binding ( using if let) to check if an optional contains the value. If the value exist , then we bind that value to the temporary local constant that only exist inside the if statement