When I create a setter such as:
var masterFrame: CGRect { set { _imageView.frame = newValue _scrollView.frame = newValue } }
It's forcing me to make a getter, which I don't want to do.
Is there any way to create a setter in Swift without a getter?
To create computed properties, Swift offers you a getter and (an optional) setter method to work with. A getter method is used to perform a computation when accessing the property. A setter method is an optional method. It can be used to modify a property that relates to the computed property.
In swift, we can create a read-only property by only defining a getter for a variable. Meaning no setter! Since the variable only has a getter, the compiler will throw an error when we try to assign a value to “sum”.
Some clarification : private in Swift works a little differently - it limits access to property/method to the scope of a file. As long as there is more then one class in a file, they will be able to access all their contents. In order for private "to work", you need to have your classess in separate files.
A getter in Swift allows access to a property, and a setter allows a property to be set.
Well if I really have to, I would use this.
Swift compiler supports some attributes on getters, so you can use @available(*, unavailable)
:
public subscript(index: Int) -> T { @available(*, unavailable) get { fatalError("You cannot read from this object.") } set(v) { } }
This will clearly deliver your intention to the code users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With