arraysswiftswift2

Find closest item in array that matches criteria in Swift?


When I have a reference to an item in an array, I'd like to find another item closest to it that matches a certain criteria (forward or backwards).

For example, I have this array:

let items = [
    (a: "Item 1", b: "F", c: 3),
    (a: "Item 2", b: "S", c: 5),
    (a: "Item 3", b: "D", c: 7),
    (a: "Item 4", b: "A", c: 9),
    (a: "Item 5", b: "M", c: 11),
    (a: "Item 6", b: "I", c: 13),
    (a: "Item 7", b: "F", c: 15),
    (a: "Item 8", b: "S", c: 17),
    (a: "Item 9", b: "D", c: 19),
    (a: "Item 10", b: "A", c: 21),
    (a: "Item 11", b: "M", c: 23),
    (a: "Item 12", b: "I", c: 13),
    (a: "Item 13", b: "F", c: 15),
    (a: "Item 14", b: "S", c: 17),
    (a: "Item 15", b: "D", c: 19),
    (a: "Item 16", b: "A", c: 21),
    (a: "Item 17", b: "M", c: 23),
    (a: "Item 18", b: "I", c: 13),
    (a: "Item 19", b: "F", c: 15),
    (a: "Item 20", b: "S", c: 17),
    (a: "Item 21", b: "D", c: 19),
    (a: "Item 22", b: "A", c: 21),
    (a: "Item 23", b: "M", c: 23),
    (a: "Item 24", b: "I", c: 13)
]

Now say I have item[7], how can I find the closest item that has b = "I"? I can only think of a few nested for loops but sounds messy and not good on performance. Also keeping in mind I don't want an out of range issue when searching. Any Swift-like ideas on how to handle this?


Solution

  • Optimised solution using higher order functions:

     func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
        return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
    }
    

    Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need.