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

iOS Object-Oriented Swift 2.0 Class Inheritance Overriding Methods

Tyler Jasper
Tyler Jasper
4,947 Points

Overriding Methods Swift 2.0. Code won't compile but does in Xcode. Whats wrong here?

It seems to work in playground. Do I need to override the first and last name init as well?

classes.swift
class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }

    func getFullName() -> String {
        return "\(firstName) \(lastName)"
    }
}
}

class Doctor : Person {

    override func getFullName() -> String {
        self.firstName = "Dr."
        return "\(firstName) \(lastName)"
    }
}
let someDoctor = Doctor(firstName: "T", lastName: "J")
someDoctor.getFullName()

2 Answers

Richard Lu
Richard Lu
20,185 Points

Hi Tyler,

The challenge wants you to have an output in the format of [Dr. ][lastName]. What you currently have is [fullName][lastName]. Another thing I want to point out is this line:

self.firstName = "Dr."

What you're doing here is assigning a constant a value which contradicts the meaning of constant. I've fixed up your code and it should work with the following snippet:

class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }

    func getFullName() -> String {
        return "\(firstName) \(lastName)"
    }
}

class Doctor : Person {
    override func getFullName() -> String {
        return "Dr. \(lastName)"    // returns "Dr. J"
    }
}

let someDoctor = Doctor(firstName: "T", lastName: "J")
someDoctor.getFullName()

If there are any questions don't hesitate to ask. Happy Coding! :D

Tyler Jasper
Tyler Jasper
4,947 Points

Thanks for the Input i appreciate it :)