示例工程 17-reflection-keypaths

17-reflection-keypaths/Sources/Ch17Kit/MirrorLab.swift

swift · 2.0 KB

/// `Mirror` 是只读反射:能看到存储属性与标签,不能写回,也看不到计算属性。
public struct Address: CustomStringConvertible {
    public let city: String
    public let zip: String
 
    public init(city: String, zip: String) {
        self.city = city
        self.zip = zip
    }
 
    public var description: String {
        "Address(\(city))"
    }
}
 
public struct Person {
    public let name: String
    public var age: Int
    public var address: Address
    public var nickname: String?
 
    public init(name: String, age: Int, address: Address, nickname: String?) {
        self.name = name
        self.age = age
        self.address = address
        self.nickname = nickname
    }
 
    /// 计算属性不会出现在 `Mirror.children` 里。
    public var displayName: String {
        nickname ?? name
    }
}
 
public enum MirrorLab {
    /// 形如 `label=value`,只保留有标签的存储属性。
    public static func describe(_ value: Any) -> [String] {
        Mirror(reflecting: value).children.compactMap { child in
            child.label.map { "\($0)=\(child.value)" }
        }
    }
 
    public static func labels(_ value: Any) -> [String] {
        Mirror(reflecting: value).children.compactMap(\.label)
    }
 
    public static func typeName(_ value: Any) -> String {
        String(describing: Mirror(reflecting: value).subjectType)
    }
 
    /// 逐层展开嵌套结构,输出 `path: type`。
    public static func shape(_ value: Any, prefix: String = "") -> [String] {
        let mirror = Mirror(reflecting: value)
        var lines: [String] = []
        for child in mirror.children {
            guard let label = child.label else { continue }
            let path = prefix.isEmpty ? label : "\(prefix).\(label)"
            lines.append("\(path): \(String(describing: type(of: child.value)))")
            if Mirror(reflecting: child.value).children.count > 0 {
                lines.append(contentsOf: shape(child.value, prefix: path))
            }
        }
        return lines
    }
}