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