It’s Friday in #swift-lang land

Question: Hi! How can I print the name of a closure. for example. I have var super = { (item: int) -> () in print(notSureWhat)} and I want print to print “super”

So Mike Ash gives an appropriate answer: “That’s the name of a variable that happens to store a reference to that closure, not the name of the closure. The closure has no idea what variables hold references to it. In short, you can’t”

Me (because it’s Friday): I bet you could use an associated object to name a closure.

And that leads to this:

Screen Shot 2015-10-23 at 12.30.58 PM

Basically, it works like this. Using @convention(block) creates an object-based block that can be cast to NSObject. Associated objects adds a custom nameTag property that’s accessible from any NSObject instance.

It is bad and I should feel bad. I know.

Update: Improved version

2 Comments