gpt4 book ai didi

swift - 如何将 try 与合并运算符一起使用?

转载 作者:搜寻专家 更新时间:2023-10-30 23:07:32 24 4
gpt4 key购买 nike

我正在尝试从函数 f 中为 x 赋值,该函数接受一个参数(一个字符串)并抛出。

当前作用域抛出异常,所以我相信 do...catch 不是必需的。

我正在尝试将 try 与合并运算符 ?? 一起使用,但出现此错误:'try' cannot appear to the right一个非赋值运算符

guard let x = try f("a") ??
try f("b") ??
try f("c") else {
print("Couldn't get a valid value for x")
return
}

如果我将 try 更改为 try?:

guard let x = try? f("a") ??
try? f("b") ??
try? f("c") else {
print("Couldn't get a valid value for x")
return
}

我收到警告 Left side of nil coalescing operator '??'具有非可选类型“String??”,因此从不使用右侧 和错误:'try?'不能出现在非赋值运算符的右边

如果我把每一个尝试?括号内:

guard let x = (try? f("a")) ??
(try? f("b")) ??
(try? f("c")) else {
print("Couldn't get a valid value for x")
return
}

它可以编译,但 x 是可选的,我希望它被解包。

如果我删除问号:

guard let x = (try f("a")) ??
(try f("b")) ??
(try f("c")) else {
print("Couldn't get a valid value for x")
return
}

我收到错误 Operator can throw but expression is not marked with 'try'

我使用的是 Swift 4.2(撰写本文时 Xcode 中的最新版本)。

x 中获取展开值的正确方法是什么?

更新:* f() 的返回类型是 String?。我认为它是一个可选字符串这一事实很重要。

最佳答案

一个try可以覆盖整个表达式,所以你可以说:

  guard let x = try f("a") ?? f("b") ?? f("c") else {
print("Couldn't get a valid value for x")
return
}

同样适用于 try?:

  guard let x = try? f("a") ?? f("b") ?? f("c") else {
print("Couldn't get a valid value for x")
return
}

虽然请注意,在 Swift 4.2 中 x 将是 String? 因为您正在将 try? 应用于已经可选的值,给你一个双重包装的可选,guard let 只会打开一层。

要解决这个问题,您可以合并为 nil:

  guard let x = (try? f("a") ?? f("b") ?? f("c")) ?? nil else {
print("Couldn't get a valid value for x")
return
}

但在 Swift 5 中这是不必要的,因为 SE-0230 ,在哪里 尝试? F A”) ?? f("b") ?? f("c") 将被编译器自动扁平化为单个可选值。

关于swift - 如何将 try 与合并运算符一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021214/

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