add a setter to a subclass in swift

You can add a setter to a subclass in Swift by using a computed property with a setter. Here's an example:

main.swift
class Person {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}

class Employee: Person {
    var salary: Double = 0.0
    
    // Use a computed property with a setter to add a custom setter
    var bonus: Double {
        get {
            return salary * 0.1 // 10% of salary
        }
        set {
            // Set the salary based on the bonus
            salary = newValue / 0.1
        }
    }
    
    override init(name: String) {
        super.init(name: name)
    }
}

let employee = Employee(name: "John")
employee.bonus = 1000.0 // This will set the salary to 10000.0
print(employee.salary) // Output: 10000.0
661 chars
31 lines

In this example, we have a Person class with a name property, and a Employee subclass that adds a salary property. We then use a computed property with a getter to calculate the bonus, and a setter to set the salary based on the bonus. We also override the init method to call the superclass init method. Finally, we create an instance of the Employee class, set the bonus property, and print the salary property to verify that it was set correctly.

gistlibby LogSnag