可以基于类使用switch语句。此类switch语句的示例代码如下所示:
let array: [Any?] = ["One", 1, nil, "Two", 2]
for item in array {
switch item {
case let anInt as Int:
print("Element is int \(anInt)")
case let aString as String:
print("Element is String \"\(aString)\"")
case nil:
print("Element is nil")
default:
break
}
}
如果需要,还可以将where子句添加到一个或多个案例中:
let array: [Any?] = ["One", 1, nil, "Two", 2, "One Hundred", 100]
for item in array {
switch item {
case let anInt as Int
where anInt < 100:
print("Element is int < 100 == \(anInt)")
case let anInt as Int where anInt >= 100:
print("Element is int >= 100 == \(anInt)")
case let aString as String:
print("Element is String \"\(aString)\"")
case nil:
print("Element is nil")
default:
break
}
}