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
==withenums with associated values. You need to use pattern matching, but that needs to be done in aswitchorifstatement.So, that leads to something ugly like this:
Notes:
You can't name your
enumTypebecause it conflicts with the built-inType. Change it to something likeMyType.It is terribly confusing to use
noneas a case in a customenumbecause it gets confused (by the humans) withnonein an optional. This is made worse by the fact that yourtypeproperty is optional. Here I have force unwrapped it, but that is dangerous of course.You could do:
This would match the
nonecase explicitly and treatnilas something you want to keep.To filter out
niland.none, you could use the nil coalescing operator??:I would suggest declaring
typeasMyClass.MyTypeinstead ofMyClass.MyType?.