Swift: Test class type in switch statement

后端 未结 4 385
日久生厌
日久生厌 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条回答
  •  暗喜
    暗喜 (楼主)
    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")
    }
    

提交回复
热议问题