Skip to content

Instantly share code, notes, and snippets.

@serhiybutz
Last active August 1, 2020 08:05
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/7232f5aa3677f4e49da0dcbbdfbd0934 to your computer and use it in GitHub Desktop.
Save serhiybutz/7232f5aa3677f4e49da0dcbbdfbd0934 to your computer and use it in GitHub Desktop.
import Foundation
final class Themer<Theme: ThemeProtocol> {
typealias TargetActionStorageType = TargetActionStorage<Theme>
private var targetActionStorages = NSHashTable<TargetActionStorageType>
.weakObjects()
var theme: Theme {
didSet {
guard theme != oldValue else { return; }
apply()
}
}
init(defaultTheme: Theme) {
self._theme = defaultTheme
}
func register<Target: AnyObject>(
target: Target,
action: @escaping (Target) -> (Theme) -> ()
) {
var storage: TargetActionStorageType
if let s = TargetActionStorageType.get(for: target) {
storage = s
} else {
storage = TargetActionStorageType.setup(for: target)
targetActionStorages.add(storage)
}
storage.register(target: target, action: action, initialTheme: theme)
}
private func apply() {
targetActionStorages.allObjects.forEach {
$0.applyTheme(theme)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment