Read-only properties of protocols in Swift

前端 未结 3 1468
时光取名叫无心
时光取名叫无心 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 21:09

    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!
    

提交回复
热议问题