/* Mutating Getter & Nonmutating Setter https://gist.github.com/hanawat/26f64afba4e6461dc27c */// Mutating GetterstructReference {privatelet _value: Double// inner value of this instancevar count =0// times this inner value has been referenced.init(value: Double) { _value = value }var value: Double { mutatingget { // ⭐️ mutating getter count +=1// mutates `count` propertyreturn _value } }}var ref =Reference(value:0.125)for_in0..<5 { print(ref.value) } // reference its value 5 times.print(ref.count)// 5
// Nonmutating SetterstructIndependent {privatestaticvar _pool = [Double]()// pool of values for this typelet index: Int// instance indexinit(value: Double) { index = Independent._pool.count Independent._pool.append(value) }// instance methodvar value: Double {// ⭐️ 注意:// 這個物件的設計從來沒有把 _pool 裡面的東西刪除,// 否則這裡的 _pool[index] 可能會出問題。get { return Independent._pool[index] }// ⭐️ nonmutating setter// instance property `index` is NOT mutated.// only TYPE property `_pool` is mutated.nonmutatingset { Independent._pool[index]= newValue } }// ⭐️ type methodstaticfuncclear() { _pool = _pool.flatMap { _in0.0 } }}// ⭐️ this is a `let`let a0 =Independent(value:0.125)print(a0.value)// 0.125a0.value=5.25// ⭐️ but its value can be changed.print(a0.value)// 5.25Independent.clear()print(a0.value)// 0.0