Swift:在switch语句中测试类类型

前端之家收集整理的这篇文章主要介绍了Swift:在switch语句中测试类类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在swift中,你可以使用’is’来检查对象的类类型。我如何将它纳入一个“开关”块?我认为这是不可能的,所以我想知道什么是最好的方法
TIA,
彼得。
你绝对可以使用是在开关块。请参阅Swift编程语言中的“Type Casting for Any和AnyObject”(尽管它不限于任何当然)。他们有一个广泛的例子:
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)")
    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相关文章