Hi,
I’m having a hard time understanding initializers and why they even exist. I have a couple of questions:
- In lesson 10, I learned about classes and subclasses. There I learned how to use so-called “templates”. I also learned you could create a new object from (like in this lesson) the Manager class for example. You can create a new manager by saying var m = Manager() and then say m.name() = “Maggie” and then create a new manager by saying n = Manager() and say n.name() = “Jonathan”
My question:
- why do initializers exist if you can do it this way? When do I declare a new object / person inside the class, when do I do it outside the class and when do I use the initializer method over the way we did it in the lesson about classes and subclasses? I realize you said that they exist to your objects are ready to be used, but what does that mean?
- In lesson 12, I get an error after writing the exact same code as in the lesson where you Chris, didn’t get an error. The code I wrote down:
import UIKit
class Person {
** var name = “”**
** init() {**
** }**
** init( name:String) {**
** self.name = name**
** }**
}
class Employee: Person {
** var salary = 0**
** var role = “”**
** override init( name:String) {**
** // This is calling the init( name:String) function of the Person class**
** super.init(name)**
** // Additional init code**
** self.role = “Analyst”**
** }**
** func doWork() {**
** print(“Hi, my name is (name) and I’m doing work.”)**
** salary += 1**
** }**
}
class Manager: Employee {
** var teamSize = 0**
** override func doWork() {**
** super.doWork()**
** print(“I’m managing people”)**
** salary += 2**
** }**
** func firePeople() {**
** print(“I’m firing people”)**
** }**
** }**
let myPerson = Person(name: “Tom”)
print(myPerson.name)
let myEmployee = Employee(name: “Joe”)
print(myEmployee.role)
print(myEmployee.name)
Xcode then gives me an error (Missing argument label ‘name:’ in call) on the line that says “super.init(name)”. I fixed this by writing down “super.init(name:name)” instead and then it works. But why is this?