var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
for item in library {
if let movie = item as? Movie {
print("Movie: (movie.name), dir. (movie.director)")
} else if let song = item as? Song {
print("Song: (song.name), by (song.artist)")
}
}
Type Casting for Any and AnyObject
Swift provides two special types for working with nonspecific types:
-
Any
can represent an instance of any type at all, including function types. -
AnyObject
can represent an instance of any class type.
To discover the specific type of a constant or variable that is known only to be of type Any
or AnyObject
, you can use an is
or as
pattern in a switch
statement’s cases. The example below iterates over the items in the things
array and queries the type of each item with a switch
statement. Several of the switch
statement’s cases bind their matched value to a constant of the specified type to enable its value to be printed:
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of (someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of (someDouble)")
case is Double:
print("some other double value that I don't want to print")
case let someString as String:
print("a string value of "(someString)"")
case let (x, y) as (Double, Double):
print("an (x, y) point at (x), (y)")
case let movie as Movie:
print("a movie called (movie.name), dir. (movie.director)")
case let stringConverter as (String) -> String:
print(stringConverter("Michael"))
default:
print("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
// Hello, Michael