Find Object with Property in Array

前端 未结 5 938
日久生厌
日久生厌 2020-11-29 02:31

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

相关标签:
5条回答
  • 2020-11-29 03:06

    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 = ""
        }
    }
    
    0 讨论(0)
  • 2020-11-29 03:13

    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})
    
    0 讨论(0)
  • 2020-11-29 03: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

    0 讨论(0)
  • 2020-11-29 03:19

    // 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 })
    
    0 讨论(0)
  • 2020-11-29 03:26

    Here is a working example in Swift 4

    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
    let firstMatchingPoint = points.first{$0.x == 1}
    
    // Find all objects with given property
    let allMatchingPoints = points.filter{$0.x == 1}
    

    Reference: Trailing Closure

    0 讨论(0)
提交回复
热议问题