Comparing objects in an Array extension causing error in Swift

后端 未结 6 517
遥遥无期
遥遥无期 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 always create an extension that uses NSArray's indexOfObject, e.g:

    extension Array {
        func indexOfObject(object:AnyObject) -> Int? {
            return (self as NSArray).indexOfObject(object)
        }
    }
    

    You can specify that your array items can be compared with the constraint, then you can cast your object into T and compare them, e.g:

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

提交回复
热议问题