Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using didSet and private(set) on Swift Array

I'm working on a swift project and I have a couple of arrays. In one of my arrays, I do not want the client to be able to mutate it without using one of my specially-defined methods. On the other hand, I want the getter to be accessible. My questions comes up regarding append and setting properties.

Question 1: Does private(set) stop clients from calling array.append?

On another array I want to see if it has been changed.

Question 2: If I add a property observer onto the array using didSet , then is the didSet called when an element is appended to the array?

like image 443
raoul Avatar asked Jul 02 '15 16:07

raoul


2 Answers

Question 1: Does private(set) stop clients from calling array.append?

Yes it does.

Question 2: If I add a property observer onto the array using didSet , then is it called when an element is appended to the array?

Yes, didSet is called when append() is called on it.

like image 148
trevorj Avatar answered Sep 22 '22 16:09

trevorj


The answers to your questions are easy to understand when you realize that arrays in Swift are effectively passed by value. I say effectively because they behave as though they are copied when they are passed, but there is some clever magic under the hood to optimize things and avoid actually needlessly duplicating elements.

The didSet handler is called when a property value changes, which in Swift includes arrays. So append()ing to an array in Swift is actually analogous to a += on an integer: the array is first read, then a new array is created with the appended value, and then that new array is written back to the property. So you can see it will definitely call didSet if you call append() on an array property, and similarly, by making set private, external users won't be able to call append() as they won't be able to write the new value back to the array.

like image 40
devios1 Avatar answered Sep 20 '22 16:09

devios1