在 init 中设置变量和 super.init 的顺序,都给出错误

Order of setting variables and super.init in init, both give errors

我有以下代码:

class EditorWindow: NSWindow {
    @Binding var keycode : Int

    override func keyDown(with event : NSEvent) {
        super.keyDown(with: event)
        Swift.print("Caught a key down: \(event.keyCode)!")
    }

    init(keycode : Int){
        self.keycode = keycode
        super.init(contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
                   styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
                   backing: .buffered, defer: false)
    }
}

将 self.keycode = 键码放在 super.init 之前给我错误消息“'self' used in 属性 access 'keycode' before 'super.init'调用”,(如 , which suggests to swap the order). If I swap the order, I get the error: "Property 'self.keycode' not initialized at super.init call" (as in this question 中建议使用 原始顺序 作为解决方案) - 似乎无论我使用哪个顺序都会出错 - 我该如何解决这个问题?

你需要传递一个Binding<Int>给构造函数:

    init(keycode : Binding<Int>){
        self._keycode = keycode
        super.init( // .....
    }