Swift code reviews: Private setters

During a code review, I learned that I was using patterns that are not really used in Swift. My previous coding experience revolves around C# so I’m used to creating a public function in order to access private properties, this was I can get their values without making them settable from outside the class.

I was doing it as follows:

class NetworkManager {
    private var networkStatus: Bool
    
    init(networkStatus: Bool) {
        self.networkStatus = networkStatus
    }
    
    func getNetworkStatus() -> Bool {
        return networkStatus
    }
}

let network = NetworkManager(networkStatus: true)
print(network.getNetworkStatus())

However, in Swift, it seems that we can just access the property directly and if we would like to have the property modified only from inside the class, we can mark these as private(set) var instead, as follows:

class NetworkManager {
    private(set) var networkStatus: Bool
    
    init(networkStatus: Bool) {
        self.networkStatus = networkStatus
    }
}

let network = NetworkManager(networkStatus: true)
print(network.networkStatus)

Leave a Reply