john doe
john doe

Reputation: 9660

Swift Protocol Getter and Setter

Why does Swift automatically allows developers to set the value of the property even though protocol has only declared a getter and not setter. Check out the following code:

import Foundation

protocol Pedometer {
    var pedometerAvailable: Bool { get } 
}

class MockPedometer: Pedometer {
    var pedometerAvailable: Bool = true // even though the Pedometer protocol is only getter I can still set ??
}

let mockPedometer = MockPedometer() 
mockPedometer.pedometerAvailable = false // why I can set the value here 

Upvotes: 0

Views: 438

Answers (1)

matt
matt

Reputation: 535201

Why

Because that's how the language works. The protocol states what the adopter must do, not what the adopter can't do. A get property must have a getter, but nothing says it cannot also have a setter.

(Looking at it from the other direction, a get set property must have both a getter and a setter; it cannot be read-only, whereas a get property can be.)

Think about it this way: the adopter must have the properties and functions specified by the protocol, but no law says that it can't have any other properties and functions; that would be ridiculous. Well, the setter is effectively another function.

Upvotes: 5

Related Questions