zmian var xyz : AnyObject
do var xyz : Any
i dodać go będzie pasował do tego przypadku
case let x as Int:
z REPL
1> var a : Any = 1
a: Int = <read memory from 0x7fec8ad8bed0 failed (0 of 8 bytes read)>
2> switch a { case let x as Int: println("int"); default: println("default"); }
int
z The Swift Programming Language
Można użyć IS i jak operatorzy w przypadkach instrukcji switch do odkryć szczególny rodzaj stałej lub zmiennej, która jest znana tylko być typu Any lub AnyObject. Poniższy przykład iteruje ponad elementów w tablicy things i zapyta o typ każdego z nich za pomocą instrukcji switch . Kilka przypadków instrukcji switch jest związać swoją dopasowaną wartość stałą określonego typu, aby umożliwić jej wartość do wydrukowania:
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)")
default:
println("something else")
}
}
// zero as an Int
// zero as a Double
// an integer value of 42
// a positive double value of 3.14159
// a string value of "hello"
// an (x, y) point at 3.0, 5.0
// a movie called 'Ghostbusters', dir. Ivan Reitman
Uwaga:
var xyz : AnyObject = 1
da ty NSNumber
ponieważ Int
nie jest obiektem, więc automatycznie przekształca go na NSNumber
, który jest obiektem
See [odpowiedź na to pytanie] [1] [1]: http://stackoverflow.com/questions/24101450/how-do-you- find-the-type-of-an-object-in-swift – kwcto
tak, uruchamia 'default:', ponieważ 'xzy' nie jest tablicą na żadnym poziomie, dlatego gałąź' default: 'będzie pasować tylko. – holex