[Solved] How to fix the setter of the fullName property to enable an automatic update for the firstName and lastName properties? [closed]


Your class is basically right (though the setter for fullName isn’t handling anything other than fullNameArr.count == 3).

class Person {
    var firstName: String            
    var lastName: String

    var fullName: String {            
        get { "\(firstName) \(lastName)" }

        set {
            let names = newValue.components(separatedBy: " ")
            lastName = names.last ?? ""
            firstName = names.dropLast().joined(separator: " ")
        }
    }

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

let person1 = Person(firstName: "Mark", lastName: "Miller")
print("first:", person1.firstName, "last:", person1.lastName)

person1.fullName = "Mary Jane Watson"
print("first:", person1.firstName, "last:", person1.lastName)

On an iPad playground, for example, that yields:

enter image description here

Note, because I did this on an iPad, I have to tap on the little icon on the right to see the output.


If you want an additional initializer that takes a full name, go ahead and add one:

init(fullName: String) {
    let names = fullName.components(separatedBy: " ")
    lastName = names.last ?? ""
    firstName = names.dropLast().joined(separator: " ")
}

Note, the above includes any middle names as part of the first name. If you really wanted to discard middle names, just grab the first name (after dropping the last name) like so:

let names = newValue.components(separatedBy: " ")
lastName = names.last ?? ""
firstName = names.dropLast().first ?? ""

Personally, I’d use struct rather than class, as we should generally use value types unless you explicitly need reference semantics. That also eliminates the need for the init method, as it will create that for us.

struct Person {
    var firstName: String            
    var lastName: String

    var fullName: String { "\(firstName) \(lastName)" }
}

var person1 = Person(firstName: "Mark", lastName: "Miller")
print(person1)

Yielding:

enter image description here

As you can see, I also eliminated the fullName setter given the ambiguity regarding what to do with middle names, prefixes (like “Dr.”), suffixes (like “M.D.”), etc. But you can do whatever you want.

0

solved How to fix the setter of the fullName property to enable an automatic update for the firstName and lastName properties? [closed]