Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mikael Van Vyve
5,298 Pointsoverruling init in a subclass and changing a superclass instance in that subclass in swift
Hi everyone,
I'm new to swift and I'm playing around with the language a little. What I'm about to ask might seem completely redundant but I would like to know a solution because it can give me a better insight in how to work with base/sub classes and change instances from the superclass.
I've been playing around for a very long time with this bit of code but can't find the sollution.
Basically what I want to do is create a subclass (Animal) that inherits from the Person class but then changes the init for the var profession to a standard init that returns a string with (species) in the string itself.
can anyone help me out with this one. I know I'd better just create a whole new base class, but fixing this problem would help me understand the class syntax much better.
Here's the code:
""" SWIFT import UIKit
class Person { var name: String var age: Int var profession: String
init(name: String, age: Int, profession: String) {
self.name = name
self.age = age
self.profession = profession
}
func whoAmI() -> String {
return "My name is \(name) and I'm \(age) old. My profession is \(profession)"
}
}
class Animal: Person { var species: String init(species: String) { self.species = species override init(name: String, age: Int, profession: String = "I'm a (species), I don't have a profession.") } override func whoAmI() -> String { return "I'm a (species) and my name is (name). I'm (age) years old." } }
var droop = Animal(species: "Dog") droop.whoAmI() """