SwiftMidOpen-ended
How do `{ get }` and `{ get set }` protocol property requirements differ?
Explanation & Code
Answer:
{ get } only requires that the property be readable, so any kind of property satisfies it, while { get set } requires a property that is both readable and writable.
Code Example:
protocol Named {
var name: String { get }
}
protocol Scored {
var score: Int { get set }
}
struct A: Named { let name: String } // ✅ stored let
struct B: Named { var name: String } // ✅ stored var
struct C: Named { var name: String { "C" } } // ✅ read-only computed
struct D: Scored { var score: Int } // ✅ stored var
struct E: Scored { // ✅ computed get + set
private var raw = 0
var score: Int {
get { raw }
set { raw = max(0, newValue) }
}
}
// struct F: Scored { let score: Int } // ❌ not settable
Key Points:
- Protocols never specify stored vs computed — only the access requirements.
{ get }is a minimum: a conforming type may still expose a setter, but code that sees only the protocol type can't use it.- Protocol property requirements are always declared with
var.
Rate your understanding: