Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Setter Only in Swift

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?

like image 344
Aggressor Avatar asked Oct 08 '14 01:10

Aggressor


People also ask

What is a setter in Swift?

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.

How do I make a Swift property read only?

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”.

What is private set Swift?

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.

What is set and get in Swift?

A getter in Swift allows access to a property, and a setter allows a property to be set.


1 Answers

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.

like image 55
eonil Avatar answered Sep 22 '22 12:09

eonil