gpt4 book ai didi

swift - 将 nil-coalescing 运算符与 try 一起使用?对于抛出并返回可选的函数

转载 作者:搜寻专家 更新时间:2023-11-01 06:50:43 26 4
gpt4 key购买 nike

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

  1. 函数抛出错误
  2. 函数返回零

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

  1. 为什么 item1 为零?
  2. 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”。

关于swift - 将 nil-coalescing 运算符与 try 一起使用?对于抛出并返回可选的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com