Programming in Swift: Functions & Types

Jan 4 2022 Swift 5.5, iOS 15, Xcode 13

Part 5: Protocols & Inheritance

39. Challenge: Inheritance

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 38. Inheritance Next episode: 40. Initializers

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

I’ve got an inheritance challenge for you! Again, everything you need is in the playground for this part of the course. Pause the video, and do your best to work through the exercises. Then, come back to see how I did things. Have fun!

class Animal {
  func speak() { }
}
class WildAnimal: Animal {
  let isPoisonous: Bool
}
  init(isPoisonous: Bool) {
    self.isPoisonous = isPoisonous
  }
}
class Pet: Animal {
  let name: String
}
  init(name: String) {
    self.name = name
  }
  func play() {
    print("Playtime! ... now naptime 💤")
  }
  override func speak() {
    print("Hi I'm \(name)! I am cute. Pet me!")
  }
class Cat: Pet {
  override func speak() {
    print("I can has Cheezeburger?")
  }
}
let animal = Animal()
let babyAragog = WildAnimal(isPoisonous: true)
let babySmaug = WildAnimal(isPoisonous: false)
let hamtaro = Pet(name: "Hamtaro")
let ozma = Cat(name: "Ozma")
let animals = [animal, babyAragog, babySmaug, hamtaro, ozma]
func printElevatorPitch(forAnimal animal: Animal) {

}
  if let animal = animal as? WildAnimal {
  
  }
    print(animal.isPoisonous ? "It's only a little poisonous!" : "It's not even poisonous!")
    return
  }
  if let pet = animal as? Pet {
    switch pet {
    
    }
    case let cat as Cat:
      print("It's a kitty named \(cat.name)! I've always wanted a kitty.")
      cat.speak()
      return
    default:
      print("This is definitely a normal sort of pet and I've named them \(pet.name).")
      pet.speak()
      pet.play()
      return
    }
  print("It's Animal! You know, the Muppet?")
}
animals.forEach(printElevatorPitch(forAnimal:))