Skip to content

Commit c677ae3

Browse files
committed
TweakStore: add new bindWeakly(:to:on:) helper
1 parent 3dec92a commit c677ae3

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

SwiftTweaks/TweakLibrary.swift

+6
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ public extension TweakLibraryType {
2929
self.defaultStore.unbind(identifier)
3030
}
3131

32+
/// Similar to `Combine.Subscribers.Assign`. returns nothing, since it doesn't strongly capture `on: OwnerObject`. example usage is:
33+
/// `ExampleTweaks.bindWeakly(ExampleTweaks.colorTint, to: \.exampleButton.backgroundColor, on: self)`
34+
static func bindWeakly<T, OwnerObject: AnyObject>(_ tweak: Tweak<T>, to keypath: ReferenceWritableKeyPath<OwnerObject, T>, on owner: OwnerObject) {
35+
self.defaultStore.bindWeakly(tweak, to: keypath, on: owner)
36+
}
37+
3238
// Accepts a collection of Tweaks, and immediately calls the updateHandler.
3339
/// The updateHandler is then re-called each time any of the collection's tweaks change.
3440
/// Inside the updateHandler, you'll need to use `assign` to get the tweaks' current values.

SwiftTweaks/TweakStore.swift

+8
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,14 @@ public final class TweakStore {
9191
tweakBindings[identifier.tweak] = existingTweakBindings.filter { $0.identifier != identifier }
9292
}
9393

94+
/// Similar to `Combine.Subscribers.Assign`. returns nothing, since it doesn't strongly capture `on: OwnerObject`. example usage is:
95+
/// `ExampleTweaks.bindWeakly(ExampleTweaks.colorTint, to: \.exampleButton.backgroundColor, on: self)`
96+
public func bindWeakly<T, OwnerObject: AnyObject>(_ tweak: Tweak<T>, to keypath: ReferenceWritableKeyPath<OwnerObject, T>, on owner: OwnerObject) {
97+
_ = self.bind(tweak) { [weak owner] tweakValue in
98+
owner?[keyPath: keypath] = tweakValue
99+
}
100+
}
101+
94102
public func bindMultiple(_ tweaks: [TweakType], binding: @escaping () -> Void) -> MultiTweakBindingIdentifier {
95103
// Convert the array (which makes it easier to call a `bindTweakSet`) into a set (which makes it possible to cache the tweakSet)
96104
let tweakSet = Set(tweaks.map(AnyTweak.init))

0 commit comments

Comments
 (0)