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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With