class MyClass: Decodable {
let title: String?
let type: MyClass.MyType?
enum MyType {
case article(data: [Article])
case link(data: [LinkTile])
case none
}
}
I would like to filter an array of MyClass
items, so the filtered array won't contain instances with type .none
let filteredArray = array.filter { $0.type != .none } // this doesn't work
Unfortunately, you can't use
==
withenum
s with associated values. You need to use pattern matching, but that needs to be done in aswitch
orif
statement.So, that leads to something ugly like this:
Notes:
You can't name your
enum
Type
because it conflicts with the built-inType
. Change it to something likeMyType
.It is terribly confusing to use
none
as a case in a customenum
because it gets confused (by the humans) withnone
in an optional. This is made worse by the fact that yourtype
property is optional. Here I have force unwrapped it, but that is dangerous of course.You could do:
This would match the
none
case explicitly and treatnil
as something you want to keep.To filter out
nil
and.none
, you could use the nil coalescing operator??
:I would suggest declaring
type
asMyClass.MyType
instead ofMyClass.MyType?
.