Comparing objects in an Array extension causing error in Swift

后端 未结 6 547
遥遥无期
遥遥无期 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:21

    You were close. Here's a working extension:

    extension Array {
        func indexOfObject(object:T) -> Int? {
            if self.count > 0 {
                for (idx, objectToCompare) in enumerate(self) {
                    if object == objectToCompare as T {
                        return idx
                    }
                }
            }
            return nil
        }
    }
    

    Swift had no way of knowing if object or objectToCompare were equatable. By adding generic information to the method, we're then in business.

提交回复
热议问题