dimanche 24 janvier 2021

Is reflection on Metatype?

While it's possible to get a list of properties from an instance: it requires an instance which is troublesome if the Type isn't trivial and doesn't have a straightforward .init(). Similarly, can't we test the existence of a nested type?

struct SomeStruct: Codable {
    var x: Int
    var y: Int
}
class CoolClass: Codable {
    var thing: SomeStruct
    var name: String
    enum CodingKeys: String, CodingKey {
        case name = "title", name = "stuff"
    }
}

func testA(_ type: Any.Type) {
    if type is Codable.Protocol {
        print("is Codable")
    } else {
        print("is NOT Codable")
    }
    let mirror = Mirror(reflecting: type)
    mirror.children  // << empty collection!!
}

func testB<T>(_ type: T.Type) where T: Codable {
    // test if `type` defines `CodingKeys` or if it is synthesized.
    
}

testA(SomeStruct.self)  // "is NOT Codable", can't get list of ["x", "y"]
                        // , nor can't get CodingKeys...

If there is no reflection for metatypes, my attempts at piggybacking off of Codable's CodingKeys (explicit or synthesized) have all failed. Is this possible?





Aucun commentaire:

Enregistrer un commentaire