Swift:在 switch 语句中测试类类型 [英] Swift: Test class type in switch statement
本文介绍了Swift:在 switch 语句中测试类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Swift 中,您可以使用is"检查对象的类类型.如何将其合并到开关"块中?
In Swift you can check the class type of an object using 'is'. How can I incorporate this into a 'switch' block?
我认为这是不可能的,所以我想知道解决这个问题的最佳方法是什么.
I think it's not possible, so I'm wondering what is the best way around this.
推荐答案
您绝对可以在 switch
块中使用 is
.请参阅 Swift Programming Language 中的Type Casting for Any and AnyObject"(当然它不限于 Any
).他们有一个广泛的例子:
You absolutely can use is
in a switch
block. See "Type Casting for Any and AnyObject" in the Swift Programming Language (though it's not limited to Any
of course). They have an extensive example:
for thing in things {
switch thing {
case 0 as Int:
println("zero as an Int")
case 0 as Double:
println("zero as a Double")
case let someInt as Int:
println("an integer value of (someInt)")
case let someDouble as Double where someDouble > 0:
println("a positive double value of (someDouble)")
// here it comes:
case is Double:
println("some other double value that I don't want to print")
case let someString as String:
println("a string value of "(someString)"")
case let (x, y) as (Double, Double):
println("an (x, y) point at (x), (y)")
case let movie as Movie:
println("a movie called '(movie.name)', dir. (movie.director)")
default:
println("something else")
}
}
这篇关于Swift:在 switch 语句中测试类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文