Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, Equatable protocol bug?

I am building a very simple structure in Swift that contains an array of optional values. This struct must conform to the Equatable protocol. This is the code:

struct MyTable: Equatable {
    var values: [Int?] = Array(count: 64, repeatedValue: nil)
}

func == (lhs: MyTable, rhs: MyTable) -> Bool {
    return lhs.values == rhs.values
}

Quite simple. I see no mistakes, but the compiler gives error: "'[Int?]' is not convertible to 'MyTable'". Am I doing something stupid? or is this a compiler's bug? Thanks!

(Using Xcode6-Beta5)

like image 733
George Avatar asked Aug 09 '26 13:08

George


1 Answers

The reason why it does not work is there is no == operator defined for arrays with optional elements, only for non-optional elements:

/// Returns true if these arrays contain the same elements.
func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool

You can provide your own:

func ==<T : Equatable>(lhs: [T?], rhs: [T?]) -> Bool {
    if lhs.count != rhs.count {
        return false
    }

    for index in 0..<lhs.count {
        if lhs[index] != rhs[index] {
            return false
        }
    }

    return true
}
like image 191
Marián Černý Avatar answered Aug 11 '26 12:08

Marián Černý



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!