class MyClass: Decodable {
let title: String?
let type: MyClass.MyType?
enum MyType {
case article(data: [Article])
case link(data: [LinkTile])
case none
}
}
我想过滤 MyClass
项的数组,因此过滤后的数组将不包含类型为 .none
的实例
let filteredArray = array.filter { $0.type != .none } // this doesn't work
最佳答案
很遗憾,您不能使用 ==
与 enum
具有相关值的 s。您需要使用模式匹配,但这需要在 switch
中完成或 if
声明。
所以,这导致了像这样丑陋的事情:
let filteredArray = array.filter { if case .none = $0.type! { return false }; return true }
注意事项:
你不能命名你的
enum
Type
因为它与内置的Type
冲突.将其更改为类似MyType
的内容.使用
none
非常困惑作为定制案例enum
因为它(被人类)混淆了none
在一个可选中。你的type
使情况变得更糟属性是可选的。在这里,我用力打开了它,但这当然很危险。你可以这样做:
if case .none? = $0.type
这将匹配
none
明确案例并对待nil
作为你想要保留的东西。过滤掉
nil
和.none
,您可以使用 nil 合并运算符??
:if case .none = ($0.type ?? .none)
我建议声明
type
作为MyClass.MyType
而不是MyClass.MyType?
.
关于swift - 通过具有关联值的枚举属性过滤项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56988742/