Anonymous class in swift

后端 未结 5 1375
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 00:30

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

5条回答
  •  不思量自难忘°
    2020-12-10 01:14

    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
    

提交回复
热议问题