KeyPathValue

使用键路径赋值的结构

示例

ReferenceWritableKeyPathValueApplier

假设我们有以下模型。

struct CALayerModel {
    var bounds: CGRect?
    var position: CGPoint?
    var frame: CGRect?

    var backgroundColor: CGColor?

    var cornerRadius: CGFloat?

    var borderWidth: CGFloat?
    var borderColor: CGColor?
}

使用 ReferenceWritableKeyPathValueApplier 定义 propertyMap

let propertyMap: [PartialKeyPath<CALayerModel>: ReferenceWritableKeyPathValueApplier<CALayer>] = [
        \.bounds: .init(\.bounds),
         \.position: .init(\.position),
         \.frame: .init(\.frame),
         \.backgroundColor: .init(\.backgroundColor),
         \.cornerRadius: .init(\.cornerRadius),
         \.borderWidth: .init(\.borderWidth),
         \.borderColor: .init(\.borderColor)
    ]

可以使用 propertyMap 赋值给对象。

extension CALayerModel {
    public func applyProperties(to target: CALayer) {
        Self.propertyMap.forEach { keyPath, applier in
            let value = self[keyPath: keyPath]
            applier.apply(value, target)
        }
    }
}