wickwirew / Runtime

A Swift Runtime library for viewing type info, and the dynamic getting and setting of properties.
MIT License
1.08k stars 94 forks source link

Is it possible to have support to closure replacement? #106

Open samcortez opened 2 years ago

samcortez commented 2 years ago

I couldn't find such information anywhere and I'm a bit stuck on this one issue. I've been trying to write a new closure over an existing closure but I haven't been successful.

This is how you can reproduce it.

func closureReplacementTest() {

    do {

        // Initialize sample data
        var freshFoo = Foo()
        let freshBar = Bar()

        // Work on getting the property
        let objectToTest = try typeInfo(of: Foo.self)
        let property = try objectToTest.property(named: "closure")

        // Replace the closure to give 100 scores instead
        try property.set(value: { (bar: Bar) in
            bar.score = 100 // Actually crashing
        }, on: &freshFoo)

        // Execute what's supposed to be the new closure
        freshFoo.closure(freshBar)

        print("Score is: \(freshBar.score)") // Expects it to be 100

    } catch {}
}

I spend a few days reading posts and documentation regarding memory management but unfortunately that's not my forte. =)

I did debug as best as I could and I noticed that during the crash the memory address of the bar variable is different that it would be when I simply run the block directly. The only thing I think it's not working quite well is the address of the variables of the closure because that's when the crash happens as the code itself of the closure seems to run just fine.

Strongly appreciate any input on this, I'll still going to spend more days trying to figure out. Thanks!