Last active
January 20, 2016 17:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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