Find Object with Property in Array

// 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 })

Leave a Comment