add a getter to a class in swift

To add a getter to a property in a Swift class, you can define the property with the get keyword. Here's an example:

main.swift
class Person {
    private var _name: String
    
    init(name: String) {
        self._name = name
    }
    
    var name: String {
        get {
            return _name
        }
    }
}
192 chars
14 lines

In this example, we have a Person class with a private property _name. We define a public computed property name with a getter method that returns the value of _name.

Note that the get keyword is optional if you define a computed property with a single-line closure:

main.swift
class Person {
    private var _name: String
    
    init(name: String) {
        self._name = name
    }
    
    var name: String { return _name }
}
152 chars
10 lines

In this example, we have the same Person class, but now the name property has a single-line closure that implicitly returns the value of _name.

gistlibby LogSnag