ios - 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
over的优点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
}
推荐阅读
- python - 如何修复太多 If return 使代码过于复杂
- c# - 我如何将 someting.split() 的一部分存储到它自己的数组中?
- ruby-on-rails - `rake assets:precompile` 在生产中时出现`babel-loader` 依赖错误
- aws-lambda - 编排 GCP 云功能
- haskell - 给出一棵树,其中每个节点的值包含子节点的总和
- flutter - 使用不包含 MainBloc 类型的 Bloc 的上下文调用 BlocProvider.of()
- gitolite - “gitolite mirror push”失败
- html - 图像 (.svg) 没有延伸到页面的整个宽度
- javascript - 我正在创建一个图像滑块,当图像设置回屏幕的另一侧时,它不会继续移动
- javascript - jQuery/NodeJS:获取没有唯一类名的按钮的 URL