https://nilliu.github.io/2016/08/16/swift3-getter-n-setter/
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import Cocoa class Human { // I specify that only the setter is private! private (set) var idNumber: String ////// USING GET/SET ///////////// private var _name : String public var name : String { get { print("Human, get name") return _name } set(newName) { print("Human, set name") _name = newName } } ////// DO THINGS BY HAND ///////////////// private var _age = 80 // getter public var age: UInt { print("get - \(#function) --> \(_age)") return UInt(_age) } public func setAge(newAge: UInt) -> Void { print("\(#function) --> \(newAge)") _age = Int(newAge) } ///////// INIT ///////////////// public init() { idNumber = String(describing: arc4random()) print("### \(#function) - Initiating \(NSStringFromClass(Human.self)) with identification number \(idNumber) ###") _name = "" } public func logStats() -> Void { print("\n\n=========== \(name) ================") print("idNumber is: \(idNumber)") print("age is: \(age)") print("============================================\n\n") } } |
Testing it
1 2 3 4 |
var human1 = Human() human1.setAge(newAge: 8) human1.name = "Ricky Tsao" human1.logStats() |
Year 2080, Cyborgs
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class Cyborg: Human { private var _suitMaterial : String = "Metal" public var suitMaterial : String { get { print("Cyborg, get suitMaterial") return _suitMaterial } set(newSuitMaterial) { print("Cyborg, set suitMaterial") _suitMaterial = newSuitMaterial } } //over-riding parent property override var name: String { get { return super.name } set (cyborgName) { // over-ride super.name = cyborgName.appending("-cyborg T2000") } } /* // before and after of parent property manipuation override var name: String { willSet(newName) { print("Cyborg, willSet name") //print("Cyborg - WillSet name to \(newName) from \(name)") } didSet { print("Cyborg, didSet name") //print("Cyborg - didSet name to \(name)") } } */ } |
Testing it
1 2 3 |
var cyborg1 = Cyborg() cyborg1.name = "Bionic Arm" cyborg1.logStats() |