1

I'm trying to understand how and why to use protocol properties. Here I've tried to create a protocol where I have dummyGet property and dummySet property. When I conform this protocol in ViewController, I can set both of those properties while dummyGet only has a "getter". What am I missing?

protocol TestProtocol {

var dummyGet: String { get }
var dummySet: String { get set }

}

class ViewController: TestProtocol {
    var dummySet: String = ""
    var dummyGet: String = ""
}
artikes123
  • 153
  • 1
  • 8
  • 2
    Of the answers on the duplicate, I consider [this](https://stackoverflow.com/a/38281806/3418066) to be the most helpful; It depends on the effective type that you are accessing. The get-only restriction only applies when you are accessing the object through the `TestProtocol` interface. When `ViewController` accesses its own properties it is doing so as an instance of `ViewController`, not through `TestProtocol`. Try `let x = ViewController() as TestProtocol; x.dummyGet="test"` and see what happens. – Paulw11 Jun 02 '22 at 07:32
  • 2
    Also note that protocols are *descriptive not restrictive*; They specify the minimum requirements, not constraints. So `dummySet` must be both gettable and settable (e.g. The requirement can't be satisfied by a constant or computed property) while `dummyGet` must be *at least* gettable and, when accessed via the protocol, cannot be assumed to be settable – Paulw11 Jun 02 '22 at 07:35
  • Great answer Paul thank you for that. What does accessing properties via protocol mean? – artikes123 Jun 02 '22 at 08:28
  • 2
    I mean when you access a variable of type `TestProtocol`. For example when I said `let x = ViewController() as TestProtocol` the inferred type of `x` is `TestProtocol`. Without the `as TestProtocol` the inferred type of `x` is `ViewController`. `dummyGet` of `ViewController` is get/set but `dummyGet` of `TestProtocol` is get only – Paulw11 Jun 02 '22 at 09:38

0 Answers0