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

kin*_*olo 185 class switch-statement swift

在Swift中,您可以使用"is"检查对象的类类型.如何将其合并到"开关"块中?

我认为这是不可能的,所以我想知道最好的方法是什么.

TIA,彼得.

Rob*_*ier 393

你绝对可以is在一个switch块中使用.请参阅Swift编程语言中的"为任何和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")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • "你绝对可以使用`is`" - 然后他从不使用它.X) (4认同)
  • 事情是在每种情况下测试的价值.因此,如果thing是Movie,它的值将被绑定到符号影片. (3认同)
  • @Raphael我可以在答案中看到`case is Double` (3认同)
  • 嗨,罗布.只是好奇心:既然我们在上面的任何一个案例中没有在switch`中使用`thing`,那么使用`thing`会有什么用呢?我没看见.谢谢. (2认同)

Abh*_*eet 44

提出"case is - case is Int,is String: "操作的示例,其中多个案例可以一起使用,以对类似对象类型执行相同的活动.这里","将类型分开,就像OR运算符一样.

switch value{
case is Int, is String:
    if value is Int{
        print("Integer::\(value)")
    }else{
        print("String::\(value)")
    }
default:
    print("\(value)")
}
Run Code Online (Sandbox Code Playgroud)

演示链接

  • 将两个案例放在一起只是为了通过`if`分隔它们可能不是证明你的观点的最好例子. (8认同)
  • 如果“value”可以是“Int”、“Float”、“Double”之一,并且以相同的方式处理“Float”和“Double”,那可能会更好。 (2认同)

Prc*_*ela 26

如果您没有值,只需要任何类:

func test(_ val:Any) {
    switch val {
    case is NSString:
        print("it is NSString")
    case is String:
        print("it is a String")
    case is Int:
        print("it is int")
    default:
        print(val)
    }
}


let str: NSString = "some nsstring value"
let i:Int=1
test(str) 
// it is NSString
test(i) 
// it is int
Run Code Online (Sandbox Code Playgroud)

更新swift 4

func test(_ val:Any) {
    switch val {
    case is NSString:
        print("it is NSString")
    case is String:
        print("it is a String")
    case is Int:
        print("it is int")
    default:
        print(val)
    }
}


let str: NSString = "some nsstring value"
let i:Int=1
test(str) 
// it is NSString
test(i) 
// it is int
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 11

我喜欢这种语法:

switch thing {
case _ as Int: print("thing is Int")
case _ as Double: print("thing is Double")
}
Run Code Online (Sandbox Code Playgroud)

因为它使您可以快速扩展功能,如下所示:

switch thing {
case let myInt as Int: print("\(myInt) is Int")
case _ as Double: print("thing is Double")
}
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢“as”,因为它也强制转换类型。 (4认同)