Read-only properties of protocols in Swift

前端 未结 3 1470
时光取名叫无心
时光取名叫无心 2020-12-06 20:39

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

protocol ExampleProtocol {
    var simpleDescription: String { get }
            


        
3条回答
  •  粉色の甜心
    2020-12-06 20:57

    Protocols place requirements on object's interface, but do not restrict implementation from providing more operations than that.

    In this example, the protocol requires a readable simpleDescription property and adjust() method. The class provides that, so it conforms to the protocol. In other words, this protocol says implementation must have get operation, but it does not prohibit them from also having set.

    You will not be able to mutate simpleDescription via that protocol interface, because it does not provide such operation, but nothing prevents you from mutating it through different interface — in this example, the interface of the implementing class.

提交回复
热议问题