Skip to content

Commit 6effecc

Browse files
committed
feat(captureAssign): Tests and improvements
1 parent 48f7835 commit 6effecc

File tree

3 files changed

+229
-157
lines changed

3 files changed

+229
-157
lines changed

Sources/Capture/Weak.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,3 +371,23 @@ extension Weak {
371371
}
372372
}
373373
}
374+
375+
extension Weak {
376+
public func captureAssign<Value>(
377+
to keyPath: ReferenceWritableKeyPath<Object, Value>
378+
) -> (Value) -> Void {
379+
capture { $0[keyPath: keyPath] = $1 }
380+
}
381+
382+
public func captureAssign<Value: Equatable>(
383+
to keyPath: ReferenceWritableKeyPath<Object, Value>,
384+
removeDuplicates isDuplicate: @escaping (Value, Value) -> Bool
385+
) -> (Value) -> Void {
386+
capture { _self, newValue in
387+
let currentValue = _self[keyPath: keyPath]
388+
if !isDuplicate(currentValue, newValue) {
389+
_self[keyPath: keyPath] = newValue
390+
}
391+
}
392+
}
393+
}

Sources/Capture/Weakifiable.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,13 @@ extension Weakifiable {
167167
public func captureAssign<Value>(
168168
to keyPath: ReferenceWritableKeyPath<Self, Value>
169169
) -> (Value) -> Void {
170-
Weak(self).capture { $0[keyPath: keyPath] = $1 }
170+
Weak(self).captureAssign(to: keyPath)
171+
}
172+
173+
public func captureAssign<Value: Equatable>(
174+
to keyPath: ReferenceWritableKeyPath<Self, Value>,
175+
removeDuplicates isDuplicate: @escaping (Value, Value) -> Bool
176+
) -> (Value) -> Void {
177+
Weak(self).captureAssign(to: keyPath, removeDuplicates: isDuplicate)
171178
}
172179
}

0 commit comments

Comments
 (0)