Bartłomiej Semańczyk Bartłomiej Semańczyk - 3 months ago 36
Swift Question

How to create a predicate to filter array of enums with associated values in Swift?

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?

Answer

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.