模式匹配并在单个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?
推荐答案
当然,您可以使用
这篇关于模式匹配并在单个Switch语句中有条件地绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文