我有一个类允许我将属性声明为Bindable
let user: Bindable<User> = Bindable(someUser)
user.update(with: someNewUser)
......
user.bind(\.name, to: label, \.text)
这样做允许将更改直接绑定到 UI 元素。
这是基于在此处找到的一篇文章
import Foundation
final class Bindable<Value> {
private var observations = [(Value) -> Bool]()
private var lastValue: Value?
init(_ value: Value? = nil) {
lastValue = value
}
}
extension Bindable {
func update(with value: Value) {
lastValue = value
observations = observations.filter { $0(value) }
}
}
extension Bindable {
// Non Optionals
func bind<O: AnyObject, T>(_ sourceKeyPath: KeyPath<Value, T>, to object: O, _ objectKeyPath: ReferenceWritableKeyPath<O, T>) {
addObservation(for: object) { object, observed in
let value = observed[keyPath: sourceKeyPath]
object[keyPath: objectKeyPath] = value
}
}
// Optionals
func bind<O: AnyObject, T>(_ sourceKeyPath: KeyPath<Value, T>, to object: O, _ objectKeyPath: ReferenceWritableKeyPath<O, T?>) {
addObservation(for: object) { object, observed in
let value = observed[keyPath: sourceKeyPath]
object[keyPath: objectKeyPath] = value
}
}
}
private extension Bindable {
func addObservation<O: AnyObject>(for object: O, handler: @escaping (O, Value) -> Void) {
// If we already have a value available, give the handler access to it directly.
lastValue.map { handler(object, $0) }
// Each observation closure returns a Bool that indicates
// whether the observation should still be kept alive,
// based on whether the observing object is still retained.
observations.append { [weak object] value in
guard let object = object else { return false }
handler(object, value)
return true
}
}
}
我想做的也是能够将属性绑定到函数。
绑定值的当前语法类似于 -
user.bind(\.name, to: label, \.text)
但我想扩展它,以便该键路径上的属性可以调用一个方法。
有点像 -
func doSomethingWithProp(_ prop: String) {
// do something
}
user.bind(\.name, to: doSomething)
在这种情况下doSomething
,可以调用一个助手NSAttributedString
并接受该name
道具作为要在该助手中使用的参数。
我在RxSwift
使用bind(onNext: ....)
.
我尝试使用 -
func bind<O: AnyObject, T, P>(_ sourceKeyPatch: KeyPath<Value, T>, to onNext: @escaping (P) -> Void) {
addObservation(for: onNext) { onNext, observed in
let value = observed[keyPath: sourceKeyPath]
onNext(value)
}
}
位我收到以下错误-
函数签名中未使用通用参数“O”
无法推断通用参数“O”