Comparing objects in an Array extension causing error in Swift

后端 未结 6 600
遥遥无期
遥遥无期 2021-01-22 15:51

I\'m trying to build an extension that adds some of the convenience functionality of NSArray/NSMutableArray to the Swift Array class, and I\'m trying to add this function:

6条回答
  •  醉酒成梦
    2021-01-22 16:17

    You can extract the compare part to another helper function, for example

    extension Array {
        func indexOfObject(object: T, equal: (T, T) -> Bool) -> Int? {
    
            if self.count > 0 {
                for (idx, objectToCompare) in enumerate(self) {
                    if equal(object, objectToCompare) {
                        return idx
                    }
                }
            }
    
            return nil
        }
    }
    
    let arr = [1, 2, 3]
    
    arr.indexOfObject(3, ==) // which returns {Some 2}
    

提交回复
热议问题