Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Switch between two optional values

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

like image 442
user2924482 Avatar asked Sep 11 '25 12:09

user2924482


1 Answers

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
    }
}
like image 126
Rob Napier Avatar answered Sep 14 '25 01:09

Rob Napier