Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 413
Bartłomiej Semańczyk Avatar asked Jun 22 '15 07:06

Bartłomiej Semańczyk


2 Answers

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.

like image 177
ncerezo Avatar answered Oct 07 '22 18:10

ncerezo


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 }
like image 20
Kádi Avatar answered Oct 07 '22 17:10

Kádi