swift中的匿名类

era*_*anh 32 anonymous-class swift

在Swift中是否有与Anonymous类相同的语法或技术?仅用于澄清Java示例中的Anonymous类 - http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

谢谢!

hpi*_*que 14

据我所知,没有相同的语法.

关于等效技术,从理论上讲,您可以使用闭包并在其中定义结构和类.可悲的是,我不能让它在游乐场或项目中工作,而不会让它崩溃.很可能这还没有准备好用于当前的测试版.

就像是...

protocol SomeProtocol {
    func hello()
}

let closure : () -> () = {
    class NotSoAnonymousClass : SomeProtocol {
        func hello() {
            println("Hello")
        }
    }
    let object = NotSoAnonymousClass()
    object.hello()
}
Run Code Online (Sandbox Code Playgroud)

...目前输出此错误:

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
Run Code Online (Sandbox Code Playgroud)


Aar*_*sen 11

您还可以创建一个基本的空类,其作用类似于裸协议,并将闭包传递给init覆盖您想要的任何内容的函数,如下所示:

class EmptyClass {

    var someFunc: () -> () = { }

    init(overrides: EmptyClass -> EmptyClass) {
        overrides(self)
    }
}

// Now you initialize 'EmptyClass' with a closure that sets
// whatever variable properties you want to override:

let workingClass = EmptyClass { ec in
    ec.someFunc = { println("It worked!") }
    return ec
}

workingClass.someFunc()  // Outputs: "It worked!"
Run Code Online (Sandbox Code Playgroud)

它在技术上并非"匿名",但它的工作方式相同.您将获得一个类的空shell,然后在使用闭包初始化它时将其填入或覆盖所需的任何参数.

它基本上是相同的,除了不满足协议的期望,它覆盖了类的属性.


Sul*_*han 9

例如,Java侦听器/适配器模式将被转换为Swift,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

(在Beta 2上破坏了编译器)

问题是,您始终必须指定名称.我不认为Apple会引入匿名类(和结构等),因为使用不会与尾随闭包冲突的语法会非常困难.

在编程匿名的事情也很糟糕.命名事物有助于读者理解代码.

  • IMO,“匿名是不好的”通常不是真的。例如,在用作回调的 lambda(或匿名类)的上下文中,它非常有用。 (4认同)

kar*_*agu 7

Swift中没有匿名类语法.但是,您可以在类和类方法中创建一个类:

class ViewController: UIViewController {

    class anonymousSwiftClass {
        func add(number1:Int, number2:Int) -> Int {
            return number1+number2;
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        class innerSwiftClass {
            func sub(number1:Int, number2:Int) -> Int {
                return number1-number2;
            }
        }

        var inner = innerSwiftClass();
        println(inner.sub(2, number2: 3));

        var anonymous = anonymousSwiftClass();
        println(anonymous.add(2, number2: 3));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 斯威夫特有时很奇怪。一方面,它迫使您在单行 `if` 语句周围放置大括号并使 switch 语句详尽无遗,但同时允许您在方法的 *body* 内定义整个类。smh (2认同)