我想在以下两种情况下使用 nil-coalescing 运算符设置默认值:
- 函数抛出错误
- 函数返回 nil
请看一下下面的代码片段。我有以下问题:
- 为什么 item1 为零?
- item1和item2的初始化有什么区别
enum VendingMachineError: Error {
case invalidCode
}
class VendingMachine {
func itemCode(code: Int) throws -> String? {
guard code > 0 else {
throw VendingMachineError.invalidCode
}
if code == 1 {
return nil
} else {
return "Item #" + String(code)
}
}
}
let machine = VendingMachine()
// Question: Why is this nil?
let item1 = try? machine.itemCode(code: 0) ?? "Unknown"
print(item1)
// nil
// What is the difference between the initialization of item1 vs item2
let item2 = (try? machine.itemCode(code: 0)) ?? "Unknown"
print(item2)
// Unknown
本质上,这与语法有关try
操作员。当与不带括号的二进制表达式一起使用时,try适用于整个二进制表达式 https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID385, 所以这:
try? machine.itemCode(code: 0) ?? "Unknown"
是相同的:
try? (machine.itemCode(code: 0) ?? "Unknown")
Since itemCode
抛出错误,表达式的后半部分?? "Unknown
被忽略,并且try?
表达式的计算结果为零。
另一方面,第二个表达式是这样的:
(try? machine.itemCode(code: 0)) ?? "Unknown"
The try?
首先计算表达式(为零),然后??
应用,将整个表达式评估为“未知”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)