4

I'm trying to implement a switch between two option values:

import UIKit

var numOne: Int?
var numTwo: Int?

func doSomething() {
    switch (numOne, numTwo) {
    case (!nil, nil):
        print("something")
    case (_ == _):
        print("equal")
    default:
        break
    }
}

doSomething()

But I'm getting this errors:

In the first case I'm getting this error:

'nil' is not compatible with expected argument type 'Bool'

in the second case I'm getting this other error:

Expression pattern of type 'Bool' cannot match values of type '(Int?, Int?)'

My question for you guys is how can I manage to generate the cases between this to optional values?

I'll really appreciate your help

user2924482
  • 8,380
  • 23
  • 89
  • 173

1 Answers1

7

There's nothing wrong here; the syntax is just incorrect.

For the first case you mean:

case (.some, .none):

There's no such things as !nil. Optionals are not Booleans. You could also write (.some, nil) since nil is an alias for .none, but that feels confusing.

For the second case you mean:

case _ where numOne == numTwo:

The point here is you mean all cases (_) where a condition is true (where ...).


func doSomething() {
    switch (numOne, numTwo) {
    case (.some, .none):
        print("something")
    case _ where numOne == numTwo:
        print("equal")
    default:
        break
    }
}
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • If I want to have this cases `case (.some, .some):` and `case _ where numOne == numTwo:` and this are the values `numTwo = 1 numOne = 1`. Only checks for the first cases. – user2924482 Apr 30 '20 at 22:07
  • Correct. The first case that succeeds is the only one matched in a `switch` statement. That's how `switch` works. If you want the `==` to be applied first, you should order it first. If you want both, you should use `if`, not `switch`. The point of `switch` is to execute exactly one `case`. – Rob Napier Apr 30 '20 at 22:29