示例工程 17-reflection-keypaths

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

swift · 1.9 KB

/// KeyPath 是类型安全的访问器值:可以传递、排序、写入。
public enum KeyPathLab {
    public static func value<Root, Value>(_ root: Root, at path: KeyPath<Root, Value>) -> Value {
        root[keyPath: path]
    }
 
    public static func set<Root, Value>(
        _ root: inout Root,
        _ path: WritableKeyPath<Root, Value>,
        to value: Value
    ) {
        root[keyPath: path] = value
    }
 
    public static func sortedByAge(_ people: [Person]) -> [Person] {
        people.sorted { $0[keyPath: \.age] < $1[keyPath: \.age] }
    }
 
    /// KeyPath 本身可以作为值存储,适合配置化的排序/过滤。
    public static var ageKeyPath: KeyPath<Person, Int> {
        \.age
    }
}
 
/// `@dynamicMemberLookup`:用点语法访问字典键,类型由下标决定。
@dynamicMemberLookup
public struct StringSettings {
    private var values: [String: String]
 
    public init(_ values: [String: String] = [:]) {
        self.values = values
    }
 
    public subscript(dynamicMember key: String) -> String? {
        get { values[key] }
        set { values[key] = newValue }
    }
 
    public var allKeys: [String] {
        values.keys.sorted()
    }
}
 
/// `@dynamicCallable`:让实例可以像函数一样调用。
@dynamicCallable
public struct Sum {
    public init() {}
 
    public func dynamicallyCall(withArguments values: [Int]) -> Int {
        values.reduce(0, +)
    }
}
 
/// 身份比较:`ObjectIdentifier` 按对象地址区分实例。
public final class Node {
    public let value: Int
 
    public init(value: Int) {
        self.value = value
    }
}
 
public enum IdentityLab {
    public static func distinctCount(_ nodes: [Node]) -> Int {
        Set(nodes.map(ObjectIdentifier.init)).count
    }
 
    public static func containsSameInstance(_ nodes: [Node], as other: Node) -> Bool {
        nodes.contains { ObjectIdentifier($0) == ObjectIdentifier(other) }
    }
}