达到"自我"在课堂上定义的闭包中

时间:2015-08-20 14:20:37

标签: ios macos swift cocoa closures

所以我有以下结构,如果可能的话,我很好奇。

class Chip8
{

    let foo = 10;

    let mapping = [

        // CLS (clear the display)
        0x00E0: { (argument: Int) -> Void in
             // How can I reach self.foo here (self.foo obviously does not work, which is the premise of the question)
         },

    ]
}

这样的事情可能吗?

编辑:

似乎如果我将映射的初始化移动到构造函数,我可以访问" self"

2 个答案:

答案 0 :(得分:3)

您也可以尝试

class Chip8
{

    let foo = 10;

    lazy var mapping:[Int: (Int)->Void] = {
        return [

            // CLS (clear the display)
            0x00E0: { (argument: Int) -> Void in
                // How can I reach self.foo here (self.foo obviously does not work, which is the premise of the question)
                self.foo
            },

        ]
    }()
}

答案 1 :(得分:1)

我已将映射的初始化移动到init构造函数,现在我可以访问" self"来自映射中的闭包。