transporter_room_3 transporter_room_3 - 7 months ago 17
Swift Question

Read-only properties of protocols in Swift

From the "Learn the Essentials of Swift" playground, there's an example protocol:

protocol ExampleProtocol {
var simpleDescription: String { get }
func adjust()
}


There's a short passage after this example that reads:


Note: The { get } following the simpleDescription property indicates that it is read-only, meaning that the value of the property can be viewed, but never changed.


Additionally an example is given of a class conforming to this protocol:

class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}

var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription


However how does this class conform to the protocol? What's stopping me from mutating
simpleDescription
? What don't I understand?

Playground screenshot

Answer

There's no way to specify in a protocol that you must have a read-only property. Your protocol asks for a simpleDescription property, and allows but does not require a setter.

Note also that the only reason you may mutate simpleDescription is because you know your a is of type SimpleClass. If we have a variable of type ExampleProtocol instead...

var a: ExampleProtocol = SimpleClass()
a.simpleDescription = "newValue" //Not allowed!