Last active
June 8, 2017 15:32
-
-
Save Dev1an/7eeaba910f91974904da6f0431b7fb54 to your computer and use it in GitHub Desktop.
Generic predicates (in Swift 4)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Sequence { | |
func find<Property, Argument>(where predicate: (propertyPath: KeyPath<Self.Element, Property>, comparator: (Property, Argument)->Bool, argument: Argument)) -> [Self.Element] { | |
return filter { predicate.comparator($0[keyPath: predicate.propertyPath], predicate.argument) } | |
} | |
// A more specialised version: | |
func find(where characteristic: KeyPath<Self.Element, Bool>) -> [Self.Element] { | |
return filter { $0[keyPath: characteristic] } | |
} | |
} | |
// Usage | |
struct Car { | |
let model: String | |
let gears: UInt8 | |
} | |
var cars = [Car]() | |
cars.find(where: (\.model, ==, "A9")) | |
cars.find(where: \.model.isEmpty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment