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 declarations
1class Animal { var name: String; init(_ n: String) { name = n } }
// Each subclass adds a method that Animal does not have
2class Dog: Animal { func bark() { print("\(name) barks!") } }
3class Cat: Animal { func meow() { print("\(name) meows!") } }
4
// Upcast: the elements are seen as Animal
5let animals: [Animal] = [Dog("Rex"), Cat("Whiskers"), Dog("Buddy")]
6
7for animal in animals {
// as? returns a Dog, or nil if the element is not one
8 if let dog = animal as? Dog {
// bark() is only available after the downcast
9 dog.bark()
// Otherwise tries Cat
10 } 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: 2
15print("\nDogs: \(animals.filter { $0 is Dog }.count)")

Output

Rex barks!
Whiskers meows!
Buddy barks!

Dogs: 2
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.

  • (× 14
  • )× 14
  • "× 12
  • {× 10
  • }× 10
  • :× 6
  • .× 4
  • \× 4
  • =× 4
  • ,× 2

More Swift examples at level 5

← Swift typing practice