有没有办法把这个if/else if/else梯子写成switch语句?
let x: Any = "123"
if let s = x as? String {
useString(s)
}
else if let i = x as? Int {
useInt(i)
}
else if let b = x as? Bool {
useBool(b)
}
else {
fatalError()
}这是我的尝试:
switch x {
case let s where s is String: useString(s)
case let i where i is Int: useInt(i)
case let b where b is Bool: useBool(b)
default: fatalError()
}它成功地选择了正确的路径,但是s/i/b仍然是Any类型。is检查在强制转换它们时没有任何效果。这迫使我在使用之前强制使用as!进行类型转换。
有没有一种方法可以在一条switch语句中打开类型并将其绑定到一个名称?
发布于 2016-08-17 00:53:37
当然,您可以使用conditional casting pattern case let x as Type
let x: Any = "123"
switch x {
case let s as String:
print(s) //use s
case let i as Int:
print(i) //use i
case let b as Bool:
print(b) //use b
default:
fatalError()
}https://stackoverflow.com/questions/38980403
复制相似问题