Type Casting in Swift
Level 5432 keystrokes
An [Animal] array holds Dogs and a Cat. as? downcasts each element to call the subclass-only method, and is counts the Dogs. The output is the three sounds, a blank line, and Dogs: 2.
Swift code
// Base class written on one line; ; separates the declarations1class Animal { var name: String; init(_ n: String) { name = n } }// Each subclass adds a method that Animal does not have2class Dog: Animal { func bark() { print("\(name) barks!") } }3class Cat: Animal { func meow() { print("\(name) meows!") } }4 // Upcast: the elements are seen as Animal5let animals: [Animal] = [Dog("Rex"), Cat("Whiskers"), Dog("Buddy")]6 7for animal in animals { // as? returns a Dog, or nil if the element is not one8 if let dog = animal as? Dog { // bark() is only available after the downcast9 dog.bark() // Otherwise tries Cat10 } else if let cat = animal as? Cat {11 cat.meow()12 }13}14 // is checks the type without casting; \n adds a blank line. Prints Dogs: 215print("\nDogs: \(animals.filter { $0 is Dog }.count)")Output
Rex barks! Whiskers meows! Buddy barks! Dogs: 2
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.
(× 14)× 14"× 12{× 10}× 10:× 6.× 4\× 4=× 4,× 2