Peter71 Peter71 - 3 months ago 27
Swift Question

Swift: reference to array element by key

I have written my own small function to find an element in an array using a key. But I'm sure there is a ready to use implementation in Swift to get it in one line. Any hint?

func objectAtKey(array: [T], key: String) -> T? {
for element in array {
if element.name == key {
return element
}
}
return nil
}


I also know function indexOf, but this return an index, I have to use for further access. I think this is slower:

let index = array.indexOf({$0.name == key})

Answer

In Swift 3 (Xcode 8, currently beta 6) you can do

if let el = array.first(where: { $0.name == key }) {
    // `el` is the first array element satisfying the condition.
    // ...
} else {
    // No array element satisfies the condition.
}

using the first(where:) method of the Sequence protocol:

/// Returns the first element of the sequence that satisfies the given
/// predicate or nil if no such element is found.
///
/// - Parameter predicate: A closure that takes an element of the
///   sequence as its argument and returns a Boolean value indicating
///   whether the element is a match.
/// - Returns: The first match or `nil` if there was no match.
public func first(where predicate: (Element) throws -> Bool) rethrows -> Element?