将 nil-coalescing 运算符与 try 一起使用?对于抛出和 returns 可选的函数
Using nil-coalescing operator with try? for function that throws and returns optional
我想在以下两种情况下使用 nil-coalescing 运算符设置默认值:
- 函数抛出错误
- 函数returns无
请查看下面的代码片段。我有以下问题:
- 为什么 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
applies to the whole binary expression,因此:
try? machine.itemCode(code: 0) ?? "Unknown"
等同于:
try? (machine.itemCode(code: 0) ?? "Unknown")
由于 itemCode
抛出错误,表达式 ?? "Unknown
的后半部分被忽略,并且 try?
表达式计算为 nil。
另一方面,第二个表达式是这样的:
(try? machine.itemCode(code: 0)) ?? "Unknown"
首先计算 try?
表达式(为 nil),然后应用 ??
,将整个表达式计算为 "Unknown".
我想在以下两种情况下使用 nil-coalescing 运算符设置默认值:
- 函数抛出错误
- 函数returns无
请查看下面的代码片段。我有以下问题:
- 为什么 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
applies to the whole binary expression,因此:
try? machine.itemCode(code: 0) ?? "Unknown"
等同于:
try? (machine.itemCode(code: 0) ?? "Unknown")
由于 itemCode
抛出错误,表达式 ?? "Unknown
的后半部分被忽略,并且 try?
表达式计算为 nil。
另一方面,第二个表达式是这样的:
(try? machine.itemCode(code: 0)) ?? "Unknown"
首先计算 try?
表达式(为 nil),然后应用 ??
,将整个表达式计算为 "Unknown".