在Swift中,你可以使用'is'来检查对象的类类型。我如何将其合并到一个“开关”块?

我认为这是不可能的,所以我想知道最好的解决办法是什么。


当前回答

如果你没有值,任何对象都可以:

斯威夫特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

其他回答

举一个“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)")
}

演示链接

我喜欢这样的语法:

switch thing {
case _ as Int: print("thing is Int")
case _ as Double: print("thing is Double")
}

因为它让你有可能快速扩展功能,就像这样:

switch thing {
case let myInt as Int: print("\(myInt) is Int")
case _ as Double: print("thing is Double")
}

你完全可以在开关块中使用。参见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")
    }
}

如果你没有值,任何对象都可以:

斯威夫特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