[英]what's the meaning of optional binding in 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
}
}
有沒有其他例子可以展示使用可選綁定的一些好處?
Optional binding
對於If Statements and Forced Unwrapping
優點:
語境:
您可以使用三種技術來處理選項:
可選綁定
您可以使用可選綁定來確定一個可選項是否包含一個值,如果包含,則將該值作為臨時常量或變量可用。 可選綁定可以與 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.