lundi 27 décembre 2021

Closure obtained from reflection cannot properly address input parameters

A hardcore Swift question I guess. Given this trivial code:

struct Container {
    let closure: (Int) -> Void
}

let container = Container { param in
    print("\(param)")
}

One can assume calling container.closure(42) will print out 42, which is true.

However, if this same closure is retrieved from the container's Mirror:

let mirror = Mirror(reflecting: container)
let closure = mirror.children
    .first(where: { $0.label == "closure" })!
    .value as! ((Int) -> Void)

... then calling closure(42) distorts the parameter's value, and it prints out 6166589480.

The same thing happens if you use String instead of Int, and I assume with other types too. If I pass a reference to an object, expectedly that reference get messed up too and I get EXC_BAD_ACCESS when trying to access the object.

Is this a bug in Swift / Xcode 13.2 or am I missing something?





Aucun commentaire:

Enregistrer un commentaire