Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Custom setter on property

Tags:

setter

swift

I am converting a project in to Swift code and have come across an issue in a setter. My Objective-C code looked like this:

- (void)setDocument:(MyDocument *)document {     if (![_document isEqual:document]) {         _document = document;          [self useDocument];     } } 

and allowed my View Controller to run this each time the document was set (typically in the prepareForSegue: method of the presenting View Controller).

I have found the property observers willSet and didSet but they only work when the property is being updated, not when it’s initialised and updated.

Any ideas? Thanks

UPDATE

after trying get{} and set{} I get the EXC_BAD_ACCESS error

var document: UIDocument? {     get {         return self.document!     }     set {         self.document = newValue          useDocument()     } } 
like image 349
Adam Carter Avatar asked Sep 13 '14 23:09

Adam Carter


People also ask

What is get set property in Swift?

Artturi Jalli In Swift, properties are either stored properties or computed properties. Getters and setters in Swift are the methods a computed property uses to either set or get a value on-demand. A stored property stores a value for later use (for example, a variable that belongs to a class instance).

What is willSet and didSet in Swift?

willSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.

How do you define getter and 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 requested. A setter method is an optional method. It can be used to modify a related property.

What is the difference between a computed property and a property set to a closure?

In short, the first is a stored property that is initialized via a closure, with that closure being called only one time, when it is initialized. The second is a computed property whose get block is called every time you reference that property.


1 Answers

You can't use set like that because when you call self.document = newValue you're just calling the setter again; you've created an infinite loop.

What you have to do instead is create a separate property to actually store the value in:

private var _document: UIDocument? = nil var document: UIDocument? {     get {         return self._document     }     set {         self._document = newValue         useDocument()     } } 
like image 82
Mike S Avatar answered Sep 17 '22 17:09

Mike S