How to compare arrays of arrays now?

Since upgrade to the new xCode, the following code does not work anymore:


func myFunc(array myArray: [[String]]) -> String
{
     if (myArray == [["N/A"]] || myArray == [[""]]) // THIS IS NOT WORKING
    { 
       ...
    }
}


showing an error that '==' cannot be applied to '[[String]]' operand anymore. What is the proper way now?


Thank you!

Replies

Why not just redefine the == operator for your purpose? Here's a generic implementation that will work for more types than just String:

func ==<E : Equatable>(lhs: [[E]], rhs: [[E]]) -> Bool {
     guard lhs.count == rhs.count else { return false }

     for i in 0..<lhs.count {
          guard lhs[i] == rhs[i] else { return false }
     }
     return true
}

To use `==` for Arrays, the Element type needs to conform to `Equatable`. Unfortunately `[String]` does not conform to `Equatable`.


Till Swift 2, Swift converted both hand side of `myArray == [["N/A"]]` to `NSArray` and applied `==` (internally calling "isEqual:") to two NSArrays.

So, even in Swift 2, you cannot compare 2D arrays which cannot be converted to `NSArray`:

enum MyEnum {
    case A, B
}
func myFunc(array myArray: [[MyEnum]]) -> String
{
    if (myArray == [[MyEnum.A]] || myArray == [[MyEnum.B]]) // THIS IS NOT WORKING
    {
        //...
    }
    //...
}


But such implicit type conversions are removed from Swift 3.


As a quick workaround, you can explicitly convert the arrays to `NSArray`:

func myFunc(array myArray: [[String]]) -> String
{
    if (myArray as NSArray == [["N/A"]] || myArray as NSArray == [[""]])
    {
        //...
    }
    //...
}

Thank you very much, guys. For the time being, I've chosen OOPer's solution, but I will deinitely check the bob133's suggestion as well.


Best!