A quick, conditional protocol error?

I am creating a very simple struct in Swift that contains an array of optional values. This structure 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
}

      

Pretty simple. I don't see any errors, but the compiler gives the error: "[Int?]" Doesn't convert to "MyTable" ". Am I doing something stupid? Or is it a compiler error? Thanks!

(Using Xcode6-Beta5)

+3


source to share


2 answers


The reason it doesn't work is there is no operator ==

defined for arrays with optional elements, only for 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
}

      

+7


source


Another useful option is to use the method elementsEqual:isEquivalent:

available in SequenceType

. This may allow you to avoid implementation Equatable

, but it is best to use it sparingly as it is more verbose.

Using:



let a: [Int?] = []
let b: [Int?] = []

if a.elementsEqual(b, isEquivalent: { $0 == $1 }) {
    print("foo") // Works
}

      

0


source







All Articles