Read Only Protocol Properties in Swift

The Learn the Essentials of Swift playground has an example protocol:

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

After this example, there is a short excerpt that states:

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

Additionally, an example of a class corresponding to this protocol is provided:

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 fit the protocol? What prevents me from mutating simpleDescription? What? I do not understand?

Playground screenshot

+4
source share
3 answers

, read- only. simpleDescription, , .

, , simpleDescription, , , a SimpleClass. ExampleProtocol ...

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

, .

simpleDescription adjust(). , . , , get, set.

simpleDescription , ​​, - .

+3

, :

, , . , , , .

Excerpt from: Apple Inc. "Fast programming language (Swift 2.2)." interactive books. https://itun.es/us/jEUH0.l

0
source

All Articles