我熟悉Swift中的switch
语句,但想知道如何用switch
替换这段代码:
if someVar < 0 {
// do something
} else if someVar == 0 {
// do something else
} else if someVar > 0 {
// etc
}
这是一种方法。假设someVar
是Int
或其他Comparable
,您可以选择将操作数分配给新变量。这允许您根据需要使用where
关键字对其进行范围调整:
var someVar = 3
switch someVar {
case let x where x < 0:
print("x is \(x)")
case let x where x == 0:
print("x is \(x)")
case let x where x > 0:
print("x is \(x)")
default:
print("this is impossible")
}
这可以简化一下:
switch someVar {
case _ where someVar < 0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
case _ where someVar > 0:
print("someVar is \(someVar)")
default:
print("this is impossible")
}
您还可以使用范围匹配完全避免使用where
关键字:
switch someVar {
case Int.min..<0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
default:
print("someVar is \(someVar)")
}
使用Swift 5,您可以选择以下开关之一来替换if语句。
PartialRangeFrom
and PartialRangeUpTo
let value = 1
switch value {
case 1...:
print("greater than zero")
case 0:
print("zero")
case ..<0:
print("less than zero")
default:
fatalError()
}
ClosedRange
and Range
let value = 1
switch value {
case 1 ... Int.max:
print("greater than zero")
case Int.min ..< 0:
print("less than zero")
case 0:
print("zero")
default:
fatalError()
}
let value = 1
switch value {
case let val where val > 0:
print("\(val) is greater than zero")
case let val where val == 0:
print("\(val) is zero")
case let val where val < 0:
print("\(val) is less than zero")
default:
fatalError()
}
_
let value = 1
switch value {
case _ where value > 0:
print("greater than zero")
case _ where value == 0:
print("zero")
case _ where value < 0:
print("less than zero")
default:
fatalError()
}
RangeExpression
protocol's ~=(_:_:)
operatorlet value = 1
switch true {
case 1... ~= value:
print("greater than zero")
case ..<0 ~= value:
print("less than zero")
default:
print("zero")
}
Equatable
protocol's ~=(_:_:)
operatorlet value = 1
switch true {
case value > 0:
print("greater than zero")
case value < 0:
print("less than zero")
case 0 ~= value:
print("zero")
default:
fatalError()
}
PartialRangeFrom
, PartialRangeUpTo
and RangeExpression
's contains(_:)
methodlet value = 1
switch true {
case (1...).contains(value):
print("greater than zero")
case (..<0).contains(value):
print("less than zero")
default:
print("zero")
}
引子盖下的switch
语句使用~=
运算符。所以这:
let x = 2
switch x {
case 1: print(1)
case 2: print(2)
case 3..<5: print(3..<5)
default: break
}
Desugars to this:
if 1 ~= x { print(1) }
else if 2 ~= x { print(2) }
else if 3..<5 ~= x { print(3..<5) }
else { }
If you look at the standard library reference, it can tell you exactly what the ~=
is overloaded to do:包括范围匹配,等同于等同的东西。 (不包括枚举大小写匹配,这是一种语言特性,而不是std lib中的函数)
您会看到它与左侧的直布尔值不匹配。对于那些比较,您需要添加where语句。
除非......你自己超载了~=
操作员。 (通常不建议这样做)一种可能性是这样的:
func ~= <T> (lhs: T -> Bool, rhs: T) -> Bool {
return lhs(rhs)
}
因此匹配一个函数,该函数在左侧返回一个布尔值,在右侧返回其参数。这是你可以用它来做的事情:
func isEven(n: Int) -> Bool { return n % 2 == 0 }
switch 2 {
case isEven: print("Even!")
default: print("Odd!")
}
对于您的情况,您可能有一个如下所示的语句:
switch someVar {
case isNegative: ...
case 0: ...
case isPositive: ...
}
但现在你必须定义新的isNegative
和isPositive
函数。除非你超载一些运营商......
您可以将正常的中缀运算符重载为curried前缀或后缀运算符。这是一个例子:
postfix operator < {}
postfix func < <T : Comparable>(lhs: T)(_ rhs: T) -> Bool {
return lhs < rhs
}
这将是这样的:
let isGreaterThanFive = 5<
isGreaterThanFive(6) // true
isGreaterThanFive(5) // false
将它与早期的函数结合使用,你的switch语句可能如下所示:
switch someVar {
case 0< : print("Bigger than 0")
case 0 : print("0")
default : print("Less than 0")
}
现在,你可能不应该在实践中使用这种东西:它有点狡猾。你(可能)更好地坚持使用where
声明。也就是说,switch语句模式
switch x {
case negative:
case 0:
case positive:
}
要么
switch x {
case lessThan(someNumber):
case someNumber:
case greaterThan(someNumber):
}
似乎很常见,值得考虑。
您可以:
switch true {
case someVar < 0:
print("less than zero")
case someVar == 0:
print("eq 0")
default:
print("otherwise")
}
由于有人已经发布case let x where x < 0:
这里是someVar
是Int
的替代品。
switch someVar{
case Int.min...0: // do something
case 0: // do something
default: // do something
}
以下是someVar
是Double
的替代方案:
case -(Double.infinity)...0: // do something
// etc
这是范围的样子
switch average {
case 0..<40: //greater or equal than 0 and less than 40
return "T"
case 40..<55: //greater or equal than 40 and less than 55
return "D"
case 55..<70: //greater or equal than 55 and less than 70
return "P"
case 70..<80: //greater or equal than 70 and less than 80
return "A"
case 80..<90: //greater or equal than 80 and less than 90
return "E"
case 90...100: //greater or equal than 90 and less or equal than 100
return "O"
default:
return "Z"
}
<0
表达式不起作用(不再?)所以我最终得到了这个:
Swift 3.0:
switch someVar {
case 0:
// it's zero
case 0 ..< .greatestFiniteMagnitude:
// it's greater than zero
default:
// it's less than zero
}
很高兴Swift 4解决了这个问题:作为3中的解决方法,我做了:
switch translation.x {
case 0..<200:
print(translation.x, slideLimit)
case -200..<0:
print(translation.x, slideLimit)
default:
break
}
工作但不理想