Swift:在switch语句中测试类类型 [英] Swift: Test class type in switch statement

查看:117
本文介绍了Swift:在switch语句中测试类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在swift中,你可以使用'is'来检查对象的类类型。我如何将它纳入一个开关块?我认为这是不可能的,所以我想知道什么是最好的方法。
TIA,
Peter。

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. TIA, Peter.

推荐答案

你绝对可以使用 code>在开关块中。请参阅Swift编程语言中的Type Casting for Any和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)")
    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆