Print property name of protocol

You can try using Mirror.

protocol MyProtocol {
    var name: String { get }
    var age: Int { get }
}

struct Person: MyProtocol {
    var name: String
    var age: Int
    var address: String
}

func getProtocolPropertyNames<T: MyProtocol>(_ object: T) -> [String] {
    let mirror = Mirror(reflecting: object)
    var propertyNames: [String] = []
    
    for child in mirror.children {
        if let propertyName = child.label {
            propertyNames.append(propertyName)
        }
    }
    return propertyNames
}

let person = Person(name: "Alice", age: 30, address: "Wonderland")
let properties = getProtocolPropertyNames(person)
print(properties) //  ["name", "age", "address"]
1 Like