首页 > 解决方案 > swift中可选绑定的含义是什么

问题描述

没有可选绑定,我们这样使用可选,看起来很乏味

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

使用可选绑定,似乎if let并没有做任何事情来减少乏味。在使用它之前,我们还有一个 if 语句要测试。

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

是否有任何其他示例可以显示使用可选绑定的一些好处?

标签: iosswift

解决方案


Optional bindingover的优点If Statements and Forced Unwrapping

  • 当结构比一层更深时,局部变量不是可选的和快捷方式

语境:

您可以使用三种技术来处理选项:

  • 可选绑定
  • If 语句和强制展开
  • 可选链接

可选绑定

您使用可选绑定来确定可选是否包含值,如果是,则使该值可用作临时常量或变量。可选绑定可以与 if 和 while 语句一起使用,以检查可选中的值,并将该值提取到常量或变量中,作为单个操作的一部分。

If 语句和强制展开

您可以使用 if 语句通过将可选项与 nil 进行比较来确定可选项是否包含值。您可以使用“等于”运算符 (==) 或“不等于”运算符 (!=) 执行此比较。

可选链接

可选链是查询和调用当前可能为 nil 的可选的属性、方法和下标的过程。如果可选包含值,则属性、方法或下标调用成功;如果可选项为 nil,则属性、方法或下标调用返回 nil。多个查询可以链接在一起,如果链中的任何链接为零,则整个链都会优雅地失败。

资源


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
}

推荐阅读