在单个 Switch 语句中进行模式匹配和条件绑定 [英] Pattern match and conditionally bind in a single Switch statement
本文介绍了在单个 Switch 语句中进行模式匹配和条件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法把这个if
/else if
/else
阶梯写成switch语句?
Is there a way to write this if
/else if
/else
ladder as a switch statement?
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!
进行强制转换.
It successfully chooses the right path, but s
/i
/b
are still of type Any
. The is
check doesn't have any effect in casting them. This forces me to force cast with as!
before usage.
有没有办法在一个 switch
语句中打开类型,并将其绑定到一个名称?
Is there a way to switch on the type, and bind it to a name, all in one switch
statement?
推荐答案
当然,您可以使用 条件转换模式 case let x as Type
:
Sure, you can use the 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()
}
这篇关于在单个 Switch 语句中进行模式匹配和条件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文