将 nil 合并运算符与 try? 用于抛出并返回可选函数



我想在以下两种情况下使用 nil-coalescing 运算符来设置默认值:

  1. 函数引发错误
  2. 函数返回 nil

请查看下面的代码片段。我有以下问题:

  1. 为什么第 1 项为零?
  2. 项目
  3. 1和项目2的初始化有什么区别
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适用于整个二进制表达式,因此:

try? machine.itemCode(code: 0) ?? "Unknown"

与以下相同:

try? (machine.itemCode(code: 0) ?? "Unknown")

由于itemCode引发错误,因此将忽略表达式?? "Unknown的后半部分,并且try?表达式的计算结果为 nil。

另一方面,第二个表达式是这样的:

(try? machine.itemCode(code: 0)) ?? "Unknown"

首先计算try?表达式(为零(,然后应用??,将整个表达式计算为"未知"。

最新更新