我定义了一个Swift枚举如下:
enum Direction {
case up
case down
case left
case right
}
然后我创建并启动这种类型的变量:
var direction: Direction = .up
和相应的可选类型的变量:
var optionalDirection: Direction? = .up
现在我想在if
语句的条件下检查特定情况:
if optionalDirection == .up {
print("Optional direction is 'up'.")
}
打印:
Optional direction is 'up'.
if direction == .down || direction == .up {
print("Direction is vertical.")
}
打印:
Direction is vertical.
然而,
if optionalDirection == .down || optionalDirection == .up {
print("Optional direction is vertical.")
}
抛出错误:
error: invalid character in source file
error: expected '{' after 'if' condition
有没有办法在不使用相当不直观的模式匹配语法(if case ...
)的情况下修复它?