Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

rbarbera commented Jun 11, 2014

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

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

@Ciechan

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.