小编典典

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

swift

在Swift中,您可以使用’is’检查对象的类类型。如何将其合并到“ switch”块中?

我认为这是不可能的,所以我想知道解决此问题的最佳方法是什么。


阅读 294

收藏
2020-07-07

共1个答案

小编典典

您绝对可以is在一个switch块中使用。请参阅Swift编程语言中的“对Any和AnyObject进行类型转换”(尽管Any当然不限于此)。他们有一个广泛的例子:

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")
    }
}
2020-07-07