Clarification of Type Casting operator in Swift required

Why is a cast (as) type operator used instead of its conditional form (how?) In this switch statement?

I thought a type operator could only be (how?) Or (how!) ...? The Apple Swift documentation does not provide an adequate explanation for this.

Here is an 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 a link to casting Apple Swift documentation

+2
source share
3 answers

You could find the answer yourself if you read the note below:

switch (, ?) . case switch.

( )

- Apple, as?, as as!.

+4

as case 0 as Int: case let someInt as Int: . Swift Language Reference case switch

case-label โ†’ case case-item-list:
โ†’ pattern guard-clause opt | pattern guard-clause opt, case-item-list

( )

โ†’ --
โ†’ --
pattern โ†’ expression-pattern

type-casting-pattern โ†’ is-pattern | -
is-pattern โ†’
as-pattern โ†’ pattern

, , ,

case let someInt as Int:
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ case-label
     โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ  case-item-list -> type-casting pattern
                    โ•ฐโ”€โ•ฏ  type
                 โ•ฐโ•ฏ      `as` keyword
     โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ         value-binding pattern
+1

Swift-:

Swift :! , " ", ? , " ".

, . , 2 as Any as! as?

In the case of a switch design, it is case let value as Type:never interrupted and there is no possibility; this value will be an optional type, unlike the expressionvalue as? Type

0
source

Source: https://habr.com/ru/post/1605756/


All Articles