Hello to the forum users this is my first post
In chapter 14 there is a Mini-Challenge in page 175, at the very end of it that says:
Make both firstName and lastName private as well. Create a way to update the students name that doesn’t involve accessing the name properties directly.
I’m a bit stuck with it and I can’t find the solution any help?
Btw Swift apprentice is an awesome Book!
Looking at this example:
print(publicString) // "Everyone can see me!" let myClass = InternalClass() myClass.sayHi() // Build error! myClass.speak() // "Hi!"
You can see hat trying to call the private function sayHi() is prohibited. Much like trying to set firstName and lastName might be once made private.
The only way to do so is to call the speak() function which is able to call the private sayHi() function.
That way you have a finer control over what functions others can call on your class.
You mark both of the Student
class firstName
and lastName
properties with the private
access control modifier and modify the student’s name in the updateName(firstName: lastName:)
method as follows:
class Student {
private var firstName: String
private var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func updateName(firstName: String, lastName: String) -> (firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
return (firstName: self.firstName, lastName: self.lastName)
}
}
let student = Student(firstName: "Ray", lastName: "Wenderlich")
let fullName = student.updateName(firstName: "Ray", lastName: "Fix")
print(fullName.firstName) // "Ray"
print(fullName.lastName) // "Fix"
Please let me know if you have any more questions or issues regarding the whole thing.