Swift provides a much more structured approach to getters and setters , then to Java.
You can, but you must not , write setters and getters, as in your code.
Instead (if you use stored properties ) just declare the property with visibility not private (e.g. internal in my example). This way, callers outside your class will be able to see the property and change it.
class Person { var name: String { willSet(newValue) { print("\(self.name) is going to be renamed as \(newValue)") } didSet(oldValue) { print("\(oldValue) has been renamed as \(self.name)") } } init(name: String) { self.name = name } }
Good, but in java getter and seters allow you to add custom logic to execute before or after changing the value.
Right! In Swift, you can do this with the willSet and didSet .
willSet (new_value)
Here you write the code that you want to run before , the new value is written to the property. Here you can access the current value (which will also be overwritten) using self.name , and the new value is available using newValue .
didSet (OldValue)
Here you write the code that you want to run after , the new value is written to the property. Here you can access the old value (which has been overwritten) with oldValue , and the new value is available in self.name .
Both willSet and didSet are optional (I'm not talking about an extra type! I mean, you are not forced to write them :).
If you do not need to run any code just before or after , the property has been changed, just omit them.
Example
let aVerySmartPerson = Person(name: "Walter White") aVerySmartPerson.name = "Heisenberg" // > Walter White is going to be renamed as Heisenberg // > Walter White has been renamed as Heisenberg
source share