Type Casting in Swift

Level 4583 keystrokes

Movie and Song are subclasses of Media stored in a [Media] array. as? tries a downcast to a subclass and returns nil on failure, so each item prints only the line for its real type: Movie by B and Song by D.

Swift code

// Base class with a title
1class Media {
2 var title: String
3 init(title: String) { self.title = title }
4}
// Subclass that adds director
5class Movie: Media {
6 var director: String
7 init(title: String, director: String) {
// Set the subclass's own property first, then call super.init
8 self.director = director
9 super.init(title: title)
10 }
11}
// Second subclass that adds artist
12class Song: Media {
13 var artist: String
14 init(title: String, artist: String) {
15 self.artist = artist
16 super.init(title: title)
17 }
18}
19
// The array's static type is Media, but each element keeps its real class
20let items: [Media] = [Movie(title: "A", director: "B"), Song(title: "C", artist: "D")]
21for item in items {
// as? Movie succeeds only for the Movie: prints Movie by B
22 if let movie = item as? Movie { print("Movie by \(movie.director)") }
// as? Song succeeds only for the Song: prints Song by D
23 if let song = item as? Song { print("Song by \(song.artist)") }
24}

Output

Movie by B
Song by D
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • :× 17
  • "× 12
  • (× 11
  • )× 11
  • {× 9
  • }× 9
  • .× 7
  • =× 6
  • ,× 5
  • ?× 2

More Swift examples at level 4

← Swift typing practice