0

I'm using Swift 1.2, and I'm having a hard time understanding why this extension does not compile. I must be missing something - T is Equatable and therefore I thought I should be able to compare via the '==' operator?

extension Array {
    func indexOf<T:Equatable>(element: T?) -> Int?
    {
        if element != nil {
            for (var i = 0; i < self.count; i++)
            {
                var val = self[i]
                if val == element! { // Error: Binary operator '==' cannot be applied to two T operands
                    return i
                }
            }
        }

        return nil
    }
}
  • 1
    As in the linked-to question, you are introducing a *new, local* placeholder type `T` in the method. Note that the possible solutions depend on the used Swift version (global function in Swift 1.2, protocol extension or restricted extension in Swift 2.0). – Martin R Aug 01 '15 at 19:21
  • 1
    Thanks Martin for pointing me in the right direction! – Cheyne Mathey-Owens Aug 02 '15 at 07:33
  • To be clear - the real issue is that the 'two T operands' described in the error are actually separate T's! It's unfortunate that Swift 1.2 does not generate errors for redefining generic types in extensions - but, I can circumvent this issue by defining a new generic type in my extension function and casting the array content to it – Cheyne Mathey-Owens Aug 02 '15 at 07:45

0 Answers0