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

10 浏览
0 Comments

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

在Swift中,您可以使用\'is\'检查对象的类类型。我怎样才能将其合并到\'switch\'块中?我认为这是不可能的,所以我想知道最好的解决方法。

admin 更改状态以发布 2023年5月21日
0
0 Comments

为了演示 case is - case is Int, is String: 操作, 可以将多个情况组合在一起,以执行相似对象类型的相同操作。在这里,"," 在 case 中起到或者运算符的作用。

switch value{
case is Int, is String:
    if value is Int{
        print("Integer::\(value)")
    }else{
        print("String::\(value)")
    }
default:
    print("\(value)")
}

演示链接

0
0 Comments

你绝对可以在 switch 代码块中使用 is。参见 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")
    }
}

0