Skip to content

Instantly share code, notes, and snippets.

@hanawat
Last active January 20, 2016 17:01
Show Gist options
  • Save hanawat/26f64afba4e6461dc27c to your computer and use it in GitHub Desktop.
Save hanawat/26f64afba4e6461dc27c to your computer and use it in GitHub Desktop.
It's also possible to use mutating or a nonmutating modifier at getter and setter in the computed property.
struct Reference {
private let _value: Double
var count = 0
init(value: Double) { _value = value }
var value: Double { mutating get {
count += 1 // Mutating property
return _value
}}
}
var reference = Reference(value: 0.125)
for _ in 0..<5 { print(reference.value) } // "0.125" is shown 5 times.
print(reference.count) // "5"
struct Independent {
private static var _pool = [Double]() // Type property
let index: Int
init(value: Double) {
index = Independent._pool.count
Independent._pool.append(value) // Add value to Array
}
var value: Double {
get { return Independent._pool[index] }
// Using only type property
nonmutating set { Independent._pool[index] = newValue }
}
static func clear() { // Type method
_pool = _pool.flatMap { _ in 0.0 }
}
}
let independent = Independent(value: 0.125)
print(independent.value) // "0.125"
independent.value = 5.25 // Possible to substitute
print(independent.value) // "5.25"
Independent.clear()
print(independent.value) // "0.0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment