Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

swift - 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?

question from:https://stackoverflow.com/questions/65876670/is-reflection-on-metatype

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know how to solve your main problem, but you are not checking correctly if type is codable. Since type is already a structure/class type (not an object), you should try to cast it from Any.Type to Codable.Type, which will only succeed if type implements Codable:

if type as? Codable.Type != nil {
    print("is Codable")
} else {
    print("is NOT Codable")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...