-2

without optional binding,we use optional like this,it seems tedious

func doSomething(str: String?)
{
    let v: String! = str
    if v != nil
    {
        // use v to do something
    }
}

with optional binding,it seems the if let doesn't do any thing to make it less tedious. we still have a if statement to test before use it.

func doSomething(str: String?)
{
    if let v = str
    {
        // use v to do something
    }
}

Is there any other examples can show some benefits to use optional bindings ?

ximmyxiao
  • 2,622
  • 3
  • 20
  • 35
  • 1
    Try optional binding of long optional chain. And variable used multiple times in the if statement. If you do so, you will get your all answers. – dahiya_boy Jan 14 '20 at 08:13
  • 2
    Quite a few [related questions](https://stackoverflow.com/search?q=%5Bswift%5D+optional+binding) which might be useful – Scriptable Jan 14 '20 at 08:13
  • Compile-time check is more important benefit I believe – The Dreams Wind Jan 14 '20 at 08:14
  • 3
    Please read the [section about Optionals](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID330) in the Language Guide – vadian Jan 14 '20 at 08:15
  • 2
    Related (if not duplicate): [When should I compare an optional value to nil?](https://stackoverflow.com/q/29717210/1187415) – Martin R Jan 14 '20 at 08:16
  • @dahiya_boy, would u say it more specificly? thanks! i don't see any need to use optional binding in optional chain – ximmyxiao Jan 14 '20 at 08:59
  • @ximmyxiao One answer is already available below which explains optional binding with optional chain. If you need further info and explanation other way, then let me know. – dahiya_boy Jan 14 '20 at 09:26
  • @dahiya_boy,thanks,seems the optional binds in optional chain saves lot of writing only ? – ximmyxiao Jan 14 '20 at 09:40
  • @ximmyxiao Yeah you are right. – dahiya_boy Jan 14 '20 at 09:53

1 Answers1

5

Advantages of the Optional binding over If Statements and Forced Unwrapping:

  • local variable which is not an optional and a shortcut when a structure is deeper than one level

Context:

You have three techniques to work with an optionals:

  • Optional binding
  • If statements and forced unwrapping
  • Optional chaining

Optional binding

You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.

If Statements and Forced Unwrapping

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).

Optional chaining

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

source


struct Computer {
    let keyboard: Keyboard?
}

struct Keyboard {
    let battery: Battery?
}

struct Battery {
    let price: Int?
}

let appleComputer: Computer? = Computer(keyboard: Keyboard(battery: Battery(price: 10)))

func getBatteryPriceWithOptionalBinding() -> Int {
    if let computer = appleComputer {
        if let keyboard = computer.keyboard {
            if let battery = keyboard.battery {
                if let batteryPrice = battery.price {
                    print(batteryPrice)
                    return batteryPrice
                }
            }
        }
    }
    return 0
}

func getBatteryPriceWithIfStatementsAndForcedUnwrapping() -> Int {
    if appleComputer != nil {
        if appleComputer!.keyboard != nil {
            if appleComputer!.keyboard!.battery != nil {
                if appleComputer!.keyboard!.battery!.price != nil {
                    print(appleComputer!.keyboard!.battery!.price!)
                    return appleComputer!.keyboard!.battery!.price!
                }
            }
        }
    }
    return 0
}

func getBatteryPriceWithOptionalChainingAndForcedUnwrapping() -> Int {
    if appleComputer?.keyboard?.battery?.price != nil {
        print(appleComputer!.keyboard!.battery!.price!)
        return appleComputer!.keyboard!.battery!.price!
    }
    return 0
}

func getBatteryPriceWithOptionalChainingAndOptionalBinding() -> Int {
    if let price = appleComputer?.keyboard?.battery?.price {
        print(price)
        return price
    }
    return 0
}

func getBatteryPriceWithOptionalChainingAndNilCoalescing() -> Int {
    print(appleComputer?.keyboard?.battery?.price ?? 0)
    return appleComputer?.keyboard?.battery?.price ?? 0
}
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93
  • Using optional binding has one major advantage. You don't need to unwrap the binded variable. That makes code easier to write. – IloneSP Jan 14 '20 at 09:18
  • 1
    thanks @Adobels,seems the optional chain with nil coalesce are the most recommended way to work with optional – ximmyxiao Jan 14 '20 at 10:08
  • @ximmyxiao yes. – Blazej SLEBODA Jan 14 '20 at 10:22
  • Returning zero instead of optional Int for price is pointless. zero it is not a valid value for price if any object in the chain is nil `var appleKeyboardBatteryPrice: Int? { appleComputer?.keyboard?.battery?.price }` – Leo Dabus Jan 14 '20 at 13:08