Willy Tan
Willy Tan

Reputation: 25

Is there a way to compare array with array using switch case in Swift?

I already tried to compare array with array with using if like this:

let ArrayA = ["A", "B"]

if ArrayA == ["A", "B"] {
   print("true")
} else {
   print("false")
}

And the result will be true, then how we do it with switch and case ? Is that possible to do it with Swift language ?

Upvotes: 1

Views: 847

Answers (2)

Alexander
Alexander

Reputation: 63264

You can use cases with where predicates:

let array = ["A", "B"]

switch array {
    case _ where array == ["A", "B"]: print("AB")
    case _ where array == ["C", "D"]: print("CD")
    default: print("default")
}

If you really wanted, you could define a pattern match operator (~=) that calls ==. The switch statement looks for definitions of the pattern match operator that accept the given pattern and candidate to determine whether a case is matched:

let array = ["A", "B"]

func ~= <T: Equatable>(pattern: [T], candidate: [T]) -> Bool {
    return pattern == candidate
}

switch array {
    case ["A", "B"]: print("AB")
    case ["C", "D"]: print("CD")
    default: print("default")
}

I would advise against this, however, because it's not clear whether such a case is doing a == check, contains(_:), hasPrefix(_:), etc.

Upvotes: 4

Suhit Patil
Suhit Patil

Reputation: 12023

Switch in Swift work with many different types but it just doesn’t match arrays out of the box. You can match arrays by overloading the ~= appropriately

func ~=<T: Equatable>(lhs: [T], rhs: [T]) -> Bool {
    return lhs == rhs
}

let ArrayA = ["A","B"]
switch ArrayA {
case (["A","B"]):
   print("true")
default:
   print("false")
}

Upvotes: 2

Related Questions