I define a Swift enumeration as follows:
enum Direction {
case up
case down
case left
case right
}
Then I create and initiate a variable of this type:
var direction: Direction = .up
and a variable of the respective optional type:
var optionalDirection: Direction? = .up
Now I want to check against particular cases in the condition of an if statement:
1. Compare optional with a single case ✅
if optionalDirection == .up {
print("Optional direction is 'up'.")
}
prints:
Optional direction is 'up'.
2. Compare non-optional with two cases ✅
if direction == .down || direction == .up {
print("Direction is vertical.")
}
prints:
Direction is vertical.
3. Compare optional with two cases ❌
However,
if optionalDirection == .down || optionalDirection == .up {
print("Optional direction is vertical.")
}
throws an error:
error: invalid character in source file
error: expected '{' after 'if' condition
Why does example 3 fail?
Is there a way to fix it without using the rather unintuitive pattern matching syntax (if case ...)?
Aucun commentaire:
Enregistrer un commentaire