75

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

5 Answers 5

161

// 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 })
Sign up to request clarification or add additional context in comments.

2 Comments

You could add the lazy function in the middle, so it should only scan the array up to the first match, and avoid the performance issue you rightly mention: let imageObject = questionImageObjects.lazy.filter{ $0.imageUUID == imageUUID }.first
Actually, questionImageObjects.first(where: { $0.imageUUID == imageUUID }) is probably the way to go with swift 3
32

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

Comments

14

Yes, you can use the filter method which takes a closure where you can set your logical expression.

Example:

struct User {
    var firstName: String?
    var lastName: String?
}

let users = [User(firstName: "John", lastName: "Doe"), User(firstName: "Bill", lastName: "Clinton"), User(firstName: "John", lastName: "Travolta")];

let johns = users.filter( { return $0.firstName == "John" } )

Note that filter returns an array containing all items satisfying the logical expression.

More info in the Library Reference

3 Comments

You can also use NSPredicate and use an NSarray.
How to filter on firstName and lastName?
@Kaptain: That should be pretty simple: replace return $0.firstName == "John" with return $0.firstName == "John" && $0.lastName == "Doe". In other words, simply rewrite/extend the closure passed to the filter, determining when an element should be included or not
11

Here is a working example in Swift 5

class Point{
    var x:Int
    var y:Int
    
    init(x:Int, y:Int){
        self.x = x
        self.y = y
    }
}

var p1 = Point(x:1, y:2)
var p2 = Point(x:2, y:3)
var p3 = Point(x:1, y:4)
var points = [p1, p2, p3]

// Find the first object with given property
// In this case, firstMatchingPoint becomes p1
let firstMatchingPoint = points.first{$0.x == 1}

// Find all objects with given property
// In this case, allMatchingPoints becomes [p1, p3]
let allMatchingPoints = points.filter{$0.x == 1}

Reference: Trailing Closure

Comments

3

Here is other way to fetch particular object by using object property to search an object in array.

if arrayTicketsListing.contains({ $0.status_id == "2" }) {
      let ticketStatusObj: TicketsStatusList = arrayTicketsListing[arrayTicketsListing.indexOf({ $0.status_id == "2" })!]
      print(ticketStatusObj.status_name)
}  

Whereas, my arrayTicketsListing is [TicketsStatusList] contains objects of TicketsStatusList class.

// TicketsStatusList class

class TicketsStatusList {
    internal var status_id: String
    internal var status_name: String
    init(){
        status_id = ""
        status_name = ""
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.