Skip to content

Instantly share code, notes, and snippets.

@Ciechan
Created June 11, 2014 12:09
Show Gist options
  • Save Ciechan/389d4174c3d41828d642 to your computer and use it in GitHub Desktop.
Save Ciechan/389d4174c3d41828d642 to your computer and use it in GitHub Desktop.
Hacky private fields
class Counter {
let inc : () -> Int
let dec : () -> Int
init(inc : () -> Int, dec : () -> Int) {
self.inc = inc;
self.dec = dec;
}
}
func CounterCreator(initial :Int) -> Counter {
var storage = initial
return Counter(inc: {return ++storage}, dec: {return --storage})
}
let c = CounterCreator(10)
c.inc() // 11
c.inc() // 12
c.dec() // 11
@rbarbera
Copy link

Using the explicit return for one line expressions, you can remove the returns from the closures

return Counter(inc: {++storage}, dec: {--storage})

@Ciechan
Copy link
Author

Ciechan commented Jun 11, 2014

Disregard this, here's a better version: https://gist.github.com/narfdotpl/838db18ea43f71c63b23

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment