Anonymous class in swift

后端 未结 5 1385
被撕碎了的回忆
被撕碎了的回忆 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:23

    For example, Java listener/adapter pattern would be translated to Swift like this:

    protocol EventListener {
        func handleEvent(event: Int) -> ()
    }
    
    class Adapter : EventListener {
        func handleEvent(event: Int) -> () {
        }
    }
    
    var instance: EventListener = {
        class NotSoAnonymous : Adapter {
            override func handleEvent(event: Int) {
                println("Event: \(event)")
            }
        }
    
        return NotSoAnonymous()
    }()
    
    instance.handleEvent(10)
    

    (Crashing the compiler on Beta 2)

    The problem is, you always have to specify a name. I don't think Apple will ever introduce anonymous classes (and structs etc.) because it would be pretty difficult to come with a syntax that doesn't collide with the trailing closures.

    Also in programming anonymous things are bad. Naming things help readers to understand the code.

提交回复
热议问题