enum EnumType {
case WithString(String)
}
var enums = [EnumType]()
enums.append(EnumType.WithString("A"))
enums.append(EnumType.WithString("B"))
enums.append(EnumType.WithString("C"))
enums.append(EnumType.WithString("D"))
enums.append(EnumType.WithString("E"))
enums.append(EnumType.WithString("F"))
How to filter my enums
array to find the one with associated value equal C
. What predicate do I need to use?
The filter function can either be invoked as a global function over an array, or as an instance method (I prefer the later as it is more OO).
It accepts a closure with one parameter (the element being evaluated) that return a boolean (indicating whether the element matches the required condition).
Since it's a simple closure in a clear situation it's ok to use the abbreviated form.
I guess that other "With" cases would be added to your enum, so you could go with something like:
let filteredArray = enums.filter {
switch $0 {
case let .WithString(value):
return value == "C"
default:
return false
}
}
That should do the trick in your example.
You could try adding a simple extension with a computed property to your enum and filter to that property:
extension EnumType {
var isC: Bool {
switch self {
case .WithString(let message): return message == "C"
default: return false
}
}
}
After this, you could simpy use the filtering as usual:
enums.filter { $0.isC }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With