Matthijn
Matthijn

Reputation: 3234

Reaching "self" in closure defined in class

So I have the following structure and was curious if this was possible.

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)
         },

    ]
}

Is something like this possible?

edit:

Seems that if I move the initialization of the mapping to the constructor I can access "self"

Upvotes: 1

Views: 56

Answers (2)

Andriy Gordiychuk
Andriy Gordiychuk

Reputation: 6272

You can also try

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
            },

        ]
    }()
}

Upvotes: 3

Matthijn
Matthijn

Reputation: 3234

I've moved the initialization of the mapping to the init constructor, and now I can access "self" from the closures in the mapping.

Upvotes: 1

Related Questions