Ever wondered how key paths can be useful in programming? Let's try to sort arrays, and find items in them, based on properties of the elements, in this case a struct
. To do so, we can create a set of generic functions and methods, and use a KeyPath
as one of the arguments, specifying the desired property of the elements in the array to process.
First, a filtering function is written. It's a generic function that simply returns a new array containing the elements from a given one, that meet the required condition. It drastically shortens the code needed to write for each case: let s2 = searchFor(property: \String.count, ==, 2, in: ["a", "ab", "abc", "cd"]) // s2 = ["ab", "cd"]
@inline(__always)
func searchFor<Root, Value>(property: KeyPath<Root, Value>, _ condition: (Value, Value) -> Bool, _ value: Value, in array: [Root]) -> [Root] {