Swift: Test class type in switch statement

后端 未结 4 376
日久生厌
日久生厌 2020-12-02 04:41

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 w

相关标签:
4条回答
  • In case you don't have a value, just any object:

    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
    
    0 讨论(0)
  • 2020-12-02 05:09

    Putting up the example for "case is - case is Int, is String:" operation, where multiple cases can be used clubbed together to perform the same activity for Similar Object types. Here "," separating the types in case is operating like a OR operator.

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

    Demo Link

    0 讨论(0)
  • 2020-12-02 05:11

    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)")
    // 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 讨论(0)
  • 2020-12-02 05:14

    I like this syntax:

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

    since it gives you the possibility to extend the functionality fast, like this:

    switch thing {
    case let myInt as Int: print("\(myInt) is Int")
    case _ as Double: print("thing is Double")
    }
    
    0 讨论(0)
提交回复
热议问题