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 trialMartel Storm
4,157 PointsOverriding Methods Code Challenge Swift 3
This is probably the most confused i've been so far. Can someone supply the answer so I can study it? Is the answer supposed to be some kind of SubClass? Man, i'm just confused as heck.
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
// Enter your code below
1 Answer
andren
28,558 PointsDid you accidentally skip the preceding video about overriding methods in swift? That video explains how overriding methods work and shows a practical example of how to do it.
Since you asked explicitly for an example of the solution I'll provide it for you, but I'd recommend you watch the video over once more.
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
// Enter your code below
class Doctor: Person { // Make a new class that inherits from the Person class.
override func fullName() -> String { // Override the fullName function
return "Dr. \(lastName)" // Provide new behavior for the function.
}
}
let someDoctor = Doctor(firstName: "FirstName", lastName: "LastName") // Instantiate the new class.
I also added some comments to clarify the code a bit.