Search code examples
swiftcomputed-properties

Computed property not computed on set


In my app, I want to allow the user to give me a Display Name when they register, but if they don't give me one, I want to create one using their first name and last initial.

This appeared to me to somewhat fit the computed property paradigm, but not exactly. I tried to do this in my class:

    var displayName: String {
    get {
        if (!self.displayName.isEmpty) {
            return self.displayName
        }
        else {
            let index = self.lastName.index((self.lastName.startIndex), offsetBy: 1)

            return self.firstName + " " + self.lastName.substring(to: index)
        }
    }
    set(displayName) {
        self.displayName = displayName
    }
}

But it crashed in several different places. Is this a correct situation for a computed property, or should I just create a regular property and check for displayName.isEmpty and set it to firstname.lastinitial if that is the case?

Thanx in advance.


Solution

  • Your app crashes for a loop issue.

    On your get you have:

    if (!self.displayName.isEmpty) {
       return self.displayName
    }
    

    I suggest you a solution like this:

    class User {
    
        private var compoundName: String
        var displayName: String {
            get {
                guard !self.compoundName.isEmpty else {
                    return self.compoundName
                } 
                if let firstLastNameChar = self.lastName.characters.first {
                     return return "\(self.firstName) \(firstLastNameChar)"
                }
                return self.firstName
            }
            set(displayName) {
                self.compoundName = displayName
            }
        }
    
    }