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 title1class Media {2 var title: String3 init(title: String) { self.title = title }4}// Subclass that adds director5class Movie: Media {6 var director: String7 init(title: String, director: String) { // Set the subclass's own property first, then call super.init8 self.director = director9 super.init(title: title)10 }11}// Second subclass that adds artist12class Song: Media {13 var artist: String14 init(title: String, artist: String) {15 self.artist = artist16 super.init(title: title)17 }18}19 // The array's static type is Media, but each element keeps its real class20let 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 B22 if let movie = item as? Movie { print("Movie by \(movie.director)") } // as? Song succeeds only for the Song: prints Song by D23 if let song = item as? Song { print("Song by \(song.artist)") }24}Output
Movie by B Song by D
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