为 switch 中的所有案例展开关联值
Unwrapping associated value for all cases in switch
我有一个与此类似的枚举,其中所有情况都包含相同的关联值 content
:
enum RowType {
case single(_ content: [Any])
case double(_ content: [Any])
case triple(_ content: [Any])
...
}
我知道我可以将 struct
与 rowType
和 content
属性一起使用,但请不要讨论这个,而是看看以下内容:
当我想切换所有的案例时,我当然可以这样做:
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
参数。
所以我很好奇并想知道:我能以某种方式 "wildcard" 枚举案例本身并仍然打开 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
我有一个与此类似的枚举,其中所有情况都包含相同的关联值 content
:
enum RowType {
case single(_ content: [Any])
case double(_ content: [Any])
case triple(_ content: [Any])
...
}
我知道我可以将 struct
与 rowType
和 content
属性一起使用,但请不要讨论这个,而是看看以下内容:
当我想切换所有的案例时,我当然可以这样做:
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
参数。
所以我很好奇并想知道:我能以某种方式 "wildcard" 枚举案例本身并仍然打开 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