Skip to content

Instantly share code, notes, and snippets.

@serhiybutz
Last active July 31, 2020 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serhiybutz/eb7519158a4f8a26335307817ae302f2 to your computer and use it in GitHub Desktop.
Save serhiybutz/eb7519158a4f8a26335307817ae302f2 to your computer and use it in GitHub Desktop.
import Foundation
fileprivate var associatedKey = "ThemerTargetActionStorage"
final class TargetActionStorage<Theme: ThemeProtocol> {
private var targetActions: [AnyTargetActionWrapper<Theme>] = []
static func setup(for target: Any) -> TargetActionStorage {
let storage = TargetActionStorage()
objc_setAssociatedObject(
target,
&associatedKey,
storage,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return storage
}
static func get(for target: Any) -> TargetActionStorage? {
return objc_getAssociatedObject(target, &associatedKey)
.map { $0 as! TargetActionStorage }
}
func register<Target: AnyObject>(
target: Target,
action: @escaping (Target) -> (Theme) -> (),
initialTheme: Theme
) {
let ta = AnyTargetActionWrapper(target: target, action: action)
targetActions.append(ta)
ta.applyTheme(initialTheme)
}
func applyTheme(_ theme: Theme) {
targetActions.forEach {
$0.applyTheme(theme)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment