Find Object with Property in Array

前端 未结 5 939
日久生厌
日久生厌 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: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})
    

提交回复
热议问题