在单个 Switch 语句中进行模式匹配和条件绑定
Pattern match and conditionally bind in a single Switch statement
有没有办法把这个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
语句中打开类型并将其绑定到名称?
当然,您可以使用 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()
}
有没有办法把这个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
语句中打开类型并将其绑定到名称?
当然,您可以使用 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()
}