Skip to content

Instantly share code, notes, and snippets.

@cozzin
Created March 15, 2018 07:11
Show Gist options
  • Save cozzin/9ae235fbc7db603522b085fe45f0f056 to your computer and use it in GitHub Desktop.
Save cozzin/9ae235fbc7db603522b085fe45f0f056 to your computer and use it in GitHub Desktop.
Undetstanding about getter and setter of protocol
// https://teamtreehouse.com/community/i-dont-understand-get-and-get-set
protocol TestProtocol {
var testVar: Int { get }
}
class TestClass: TestProtocol {
var testVar: Int = 0
}
// As Swift knows that this is a TestClass,
// we can set it without any errors
let testObject = TestClass()
testObject.testVar = 1
// We could, however, have an array of objects that conform to TestProtocol
// These objects could be of any class, the only thing that we know for sure is
// that the getter for testVar is defined, it could be a regular variable or a
// computed property, or even a public var with a private setter
let testArr: [TestProtocol] = [testObject]
// We know that this is a TestClass and it has a setter, we set it just a few lines before.
// However, an exception will be thrown if we try to set it now, as Swift only knows this object
// conforms to TestProtocol and a setter might not be implemented
var aClassThatConformsToTestProtocol = testArr[0]
aClassThatConformsToTestProtocol.testVar = 10 // Error
// If you change the protocol to
protocol TestProtocol {
var testVar: Int { get set }
}
// it can be set without errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment