Created
June 3, 2015 19:25
-
-
Save airspeedswift/9788eab1eaf887f65ab7 to your computer and use it in GitHub Desktop.
subscript mutation example
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
extension Int { | |
mutating func increment() { | |
self = self.successor() | |
} | |
} | |
struct S { | |
var x: Int = 0 | |
subscript()->Int { | |
get { | |
println("getting x: x is \(x)") | |
return x | |
} | |
set(newVal) { | |
println("setting x to \(newVal)") | |
x = newVal | |
} | |
} | |
} | |
var s = S() | |
s[].increment() | |
func f(inout i: Int) { | |
println("i is \(i)") | |
println("about to set i to 42") | |
i = 42 | |
println("about to set i to 100") | |
i = 100 | |
println("about to exit f()") | |
// note, only on exit will the | |
// subscript set be called | |
} | |
f(&s[]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment