Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Created June 3, 2015 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/9788eab1eaf887f65ab7 to your computer and use it in GitHub Desktop.
Save airspeedswift/9788eab1eaf887f65ab7 to your computer and use it in GitHub Desktop.
subscript mutation example
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