Search code examples
swiftcastingtypecasting-operator

Need clarification of Type Casting operator in Swift


Why is the type cast operator (as) being used instead of its conditional form (as?) in this switch statement?

I thought the type operator could only be (as?) or (as!)...? The Apple Swift documentation does not provide adequate explanation about this.

Here is the example in the Swift documentation:

var things = [Any]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" }) 

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)")
        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)")
        case let stringConverter as String -> String:
            println(stringConverter("Michael"))
        default:
            println("something else")
        }
    }

Here is the link to the Apple Swift documentation on Type Casting


Solution

  • You could have found the answer yourself if you read the note on the bottom:

    The cases of a switch statement use the forced version of the type cast operator (as, not as?) to check and cast to a specific type. This check is always safe within the context of a switch case statement.

    (emphasis mine)

    Here is an Apple blog post which elaborates on the difference between as?, as and as!.