Find Object with Property in Array

Solution 1:

// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?

You have no way to prove at compile-time that there is only one possible result on an array. What you're actually asking for is the first matching result. The easiest (though not the fastest) is to just take the first element of the result of filter:

let imageObject = questionImageObjects.filter{ $0.imageUUID == imageUUID }.first

imageObject will now be an optional of course, since it's possible that nothing matches.

If searching the whole array is time consuming, of course you can easily create a firstMatching function that will return the (optional) first element matching the closure, but for short arrays this is fine and simple.


As charles notes, in Swift 3 this is built in:

questionImageObjects.first(where: { $0.imageUUID == imageUUID })

Solution 2:

Edit 2016-05-05: Swift 3 will include first(where:).

In Swift 2, you can use indexOf to find the index of the first array element that matches a predicate.

let index = questionImageObjects.indexOf({$0.imageUUID == imageUUID})

This is bit faster compared to filter since it will stop after the first match. (Alternatively, you could use a lazy sequence.)

However, it's a bit annoying that you can only get the index and not the object itself. I use the following extension for convenience:

extension CollectionType {
    func find(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
        return try indexOf(predicate).map({self[$0]})
    }
}

Then the following works:

questionImageObjects.find({$0.imageUUID == imageUUID})