gpt4 book ai didi

swift - 在 Swift switch 中提取值

转载 作者:行者123 更新时间:2023-11-30 12:21:26 25 4
gpt4 key购买 nike

在 Swift 中是否可以同时进行模式匹配和提取初始值(现在转换)?

例如,如果我有这些枚举:

enum Inner {
case a(Int)
case b(Int)
}

enum Outer {
case one
case two(Inner)
}

我想匹配Outer.two(Inner.a(1))并且同时有一个变量转换为它

let value: Any // Could be anything :|

switch value {
case let a as Outer.two(Inner.a(1)):
// Do something which needs `a`
default"
// Do some other things
}

显然,这不起作用,因为 as 只能转换为类型。

我也尝试过

case Outer.two(let a) where a == Inner.a(1):
case let Outer.two(.a(1)) = a: // i.e. the syntax in "guard case let ..."

这不起作用。 (注意第一个可以工作,但实现 == 对我来说不是一个选择,烦人)

仅供引用:Scala 允许您使用 @ 运算符来完成此操作,如下所示:

case a @ Outer.two(Inner.a(1)):

是否有一种语法可以做到这一点,或者我是否需要重新考虑如何解决我的问题?

最佳答案

我认为没有等效的模式 case a @ Outer.two(Inner.a(1)):在 swift .这是一个可能的解决方法:

switch value {
case Outer.two(Inner.a(1)):
let a = Inner.a(1)
// Do something which needs `a`
default:
// Do some other things
}

关于swift - 在 Swift switch 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747207/

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