[Solved] How translate to Swift an anonymous class of Java? [closed]

Mostly this syntax (inline definition of anonymous classes) exists because Java doesn’t allow the concept of closures or lambda functions, so if you want to pass a function to be invoked you have to pass an instance of a class with the function then declared inline.

In contrast, Swift, like most modern languages has a specific closure syntax which allows you to directly pass executable blocks to another routine, essentially it allows you to treat functions as first class language entities.

So, the bottom line is that no, Swift doesn’t allow the construct you’ve asked about, but it does provide equivalent functionality for the dominant use case. The code most analogous to your example would be:

dispatch_async(...) {
    Code to be executed asynchronously here

Which is really just syntactic sugar for:

dispatch_async(..., {
    Your code here

Since the anonymous object is being created only as a holder for a single object, there’s really no need for the object, or indeed, the class, and hence the syntax. The only time the Java syntax has a slight advantage is if the callee needs to maintain multiple related callbacks.


solved How translate to Swift an anonymous class of Java? [closed]