gpt4 book ai didi

swift - 为 switch 中的所有案例展开关联值

转载 作者:行者123 更新时间:2023-11-28 05:39:14 25 4
gpt4 key购买 nike

我有一个与此类似的枚举,其中所有情况都包含相同的关联值 content:

enum RowType {
case single(_ content: [Any])
case double(_ content: [Any])
case triple(_ content: [Any])
...
}

我知道我可以只使用带有 rowTypecontent 属性的 struct,但请不要讨论这个,而是看看以下内容:当我想切换所有案例时,我当然可以这样做:

switch row {
case .single(let content):
// do anything
break
case .double(let content):
// ...
...
}

甚至:

switch row {
case .single(let content), .double(let content), ...:
// do the same thing for all cases
break
}

现在我的枚举包含更多案例,并且在开发过程中可能会进一步增长,所以我不方便在同一个 case 语句中列出所有案例,只是为了展开 content 参数。

所以我很好奇并想知道:我能否以某种方式“通配符”枚举案例本身并仍然打开 content 字段? 就像 default 具有关联值的案例...

我希望能够做类似的事情 ...

switch row {
case _(let content):
// do something
break
}

... 或者在默认情况下访问关联值。

我做了一些研究,但找不到答案,所以我很期待你的想法。

最佳答案

在 Playground 中试试这个。

enum RowType {
case single(_ content: [Any])
case double(_ content: [Any])
case triple(_ content: [Any])
case noVal

var associatedValue: Any? {
get {
let mirror = Mirror(reflecting: self)
if let associated = mirror.children.first {
return associated.value
}
print("WARNING: Enum option of \(self) does not have an associated value")
return nil
}
}
}

let row : RowType = .double([1,2,3])
let rowNoVal : RowType = .noVal
row.associatedValue
rowNoVal.associatedValue

关于swift - 为 switch 中的所有案例展开关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506429/

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