add a setter to a class in swift

To add a setter to a class in Swift, you need to define a variable using the var keyword and specify its data type. You can then provide a set method to modify the variable's value.

Here is an example class with a setter:

main.swift
class Person {
    var name: String {
        didSet {
            print("Name has been updated to \(name)")
        }
    }
    
    init(name: String) {
        self.name = name
    }
}

let person = Person(name: "John")
person.name = "Jane" // output: "Name has been updated to Jane"
287 chars
15 lines

In this example, a Person class is defined with a name property. The set method inside the didSet block is called once the name property is updated.

When you create an instance of the Person class, you can set the name property and the set method will be triggered, outputting the message "Name has been updated to [name]".

gistlibby LogSnag