Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous class in swift

Is there an equivalent syntax or technique for Anonymous class in Swift? Just for clarification Anonymous class in Java example here - http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Thanks!

like image 214
eranh Avatar asked Jun 25 '14 11:06

eranh


People also ask

How do you make an anonymous class in Swift?

Simply use a struct for defining the interface via function values and then anonymously implement it from a function, as is a very common way to write objects in JavaScript. The function is only required for creating a private scope for the object returned.

What is anonymous class used for?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

What are anonymous classes?

A nested class that doesn't have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class. Its syntax is: class outerClass { // defining anonymous class object1 = new Type(parameterList) { // body of the anonymous class }; }

Is anonymous class private?

An anonymous class cannot define any static fields, methods, or classes, except for staticfinal constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.


1 Answers

There is no equivalent syntax, as far as I know.

Regarding equivalent techniques, theoretically you could use closures and define structs and classes inside them. Sadly, I can't get this to work in a playground or project without making it crash. Most likely this isn't ready to be used in the current beta.

Something like...

protocol SomeProtocol {     func hello() }  let closure : () -> () = {     class NotSoAnonymousClass : SomeProtocol {         func hello() {             println("Hello")         }     }     let object = NotSoAnonymousClass()     object.hello() } 

...currently outputs this error:

invalid linkage type for global declaration %swift.full_heapmetadata* @_TMdCFIv4Test7closureFT_T_iU_FT_T_L_19NotSoAnonymousClass LLVM ERROR: Broken module found, compilation aborted! Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 1 
like image 64
hpique Avatar answered Oct 11 '22 16:10

hpique