How to create a predicate for filtering an array of enumerations with related 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 a value with an associated value equal to C Which predicate should I use?

+5
source share
4 answers

The filter function can be called as a global function over an array or as an instance method (I prefer later ones, since this is more OO).

It takes a closure with one parameter (evaluated element), which returns a boolean value (indicates whether the element meets the required condition).

Since this is a simple closure in a clear situation, an abbreviated form can be used.

I assume that other C cases will be added to your listing, so you can go with something like:

 let filteredArray = enums.filter { switch $0 { case let .WithString(value): return value == "C" default: return false } } 

This should do the trick in your example.

+5
source

As already mentioned, if case expression is available for Swift> 2.0:

 enums.filter { if case .WithString("C") = $0 { return true } return false } 

But this does not look very good, especially if you repeat the same logic again. Here we can make EnumType match Equatable:

 extension EnumType: Equatable { } func ==(lhs: EnumType, rhs: EnumType) -> Bool { switch (lhs, rhs) { case (.WithString(let lStr), .WithString(let rStr)): return lStr == rStr } } 

And now you can simply:

 enums.filter { $0 == .WithString("C") } 
+6
source
 var filteredArray = enums.filter { element in switch element { case EnumType.WithString(let string): return string == "A" default: return false } } 

This can be simplified by binding Swift 2.0 associated values ​​in if .

0
source

You can try adding a simple extension with a computed property to your enumeration and filtering for this property:

 extension EnumType { var isC: Bool { switch self { case .WithString(let message): return message == "C" default: return false } } } 

After that, you can simply use filtering as usual:

 enums.filter { $0.isC } 
0
source

All Articles