mardi 23 mai 2023

Get properties types of Class.Type in Swift

I want to retrieve all classes that confirm specific protocol

protocol Service: NSObject {}

and then build a dictionary

[ClassName: [String array of property types]].

I managed to retrieve all classes using obj c reflection:

    private static func allClasses<R>() -> [R] {
        var count: UInt32 = 0
        let classListPtr = objc_copyClassList(&count)
        defer {
            free(UnsafeMutableRawPointer(classListPtr))
        }
        let classListBuffer = UnsafeBufferPointer(start: classListPtr, count: Int(count))

        return classListBuffer.compactMap { $0 as? R }
    }

But I have problems with retrieving property types of services. From what I see Swift API requires object to get that info

Mirror(reflecting: obj).children

and even tho my protocol requires NSOject I don't want to create object just to retrieve properties. Is there any other way to achieve it? From what I saw there is obj-c method class_copyPropertyList but you can only retrieve name and attributes with that, and you still need the object to get property types.





Aucun commentaire:

Enregistrer un commentaire