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:
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
This is bad and you should feel bad! https://www.youtube.com/watch?v=jG2KMkQLZmI The original is gross but I really like the improved version! I’d love to have a conversation with you on precisely how this works since I’m not quite sure if I understand!
Oh I forgot to mention I was joking in my earlier comment.