derdida derdida - 6 months ago 74
Swift Question

Find Object with Property in Array

is there a possibility to get an object from an array with an specific property? Or do i need to loop trough all objects in my array and check if an property is the specific i was looking for?

edit: Thanks for given me into the correct direction, but i have a problem to convert this.

// edit again: A ok, and if there is only one specific result? Is this also a possible method do to that?

let imageUUID = sender.imageUUID


let questionImageObjects = self.formImages[currentSelectedQuestion.qIndex] as [Images]!

// this is working
//var imageObject:Images!
/*
for (index, image) in enumerate(questionImageObjects) {

if(image.imageUUID == imageUUID) {
imageObject = image
}

}
*/

// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?
var imageObject = questionImageObjects.filter( { return $0.imageUUID == imageUUID } )

Answer

// 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.

Comments