Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 5: Protocols & Inheritance

39. Challenge: Inheritance

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 39. Challenge: Inheritance

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.

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:))