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

Optional Kind #45

Closed cyber-gh closed 5 years ago

cyber-gh commented 5 years ago

So i've got a class where most of the properties are optional and I'm trying to set their values. Is it possible to set the value of an optional kind property? When i currently try it throws an RuntimeError.couldNotGetPointer. Is there a workaround to cast it as non-optional or something like that?

Thanks in advance

wickwirew commented 5 years ago

Thanks for the issue! I'm having trouble reproducing this. Could you provide a test case?

I've tried this and it passes.

func testOptionalProperty() throws {
    class TestOptional {
        var a: Int?
    }

    let info = try typeInfo(of: TestOptional.self)
    let property = try info.property(named: "a")

    var obj = TestOptional()
    try property.set(value: 5, on: &obj)

    XCTAssertEqual(5, obj.a)
}
cyber-gh commented 5 years ago

I'm sorry, it was my bad, didn't understand the thrown error. Apparently i was calling property.set on an optional object. Force unwrapping solved the problem. try property.set(value: 5, on: &obj!)