Better Getters & Setters with observers in Swift

Create Getters & Setters

Better Getters & Setters with observers in Swift… Wow, try to say this three times fast without twisting your tongue.

Ok, whatever.

Using Getter/Setter methods in Swift is pretty straight forward and looks familiar for if you have experience in other languages like Java, C# or ActionScript etc. But an interesting thing is Swifts observer functionality that gives you more control over these methods. But first we look at the standard way we use getters/setters in other programming languages.

In case you ask yourself were the newValue is coming from: The newValue is set by default if no parameter is defined by the Setter method.

Swift

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

// Class definition

classMyVector

{

varx=0;vary=0

varhalfX: Int

{

get

{

returnx/2

}

set

{

x=2*newValue

}

}

}

// Testing MyVector class getters & setters

varv2:MyVector=MyVector()

print("V2 => x:\(v2.x), y:\(v2.y), halfX:\(v2.halfX)")

v2.halfX=10;

print("V2 => x:\(v2.x), y:\(v2.y), halfX:\(v2.halfX)")

[adinserter block=”10″]

Property observers

Ok, and now the fancy new stuff: Observers allow you to execute code when a value is set via setter method. For this there are the keywords: willSet and didSet. In the example below the Setter is printing a message when it is about to set a new value using the willSet statement. Further the Setter checks if the new value is greater 100 and corrects the value if this is the case. This is done by using the didSet statement.