Skip to content

Instantly share code, notes, and snippets.

@FranDepascuali
Last active April 7, 2022 18:37
Show Gist options
  • Save FranDepascuali/9f0a10c4823897911ad1 to your computer and use it in GitHub Desktop.
Save FranDepascuali/9f0a10c4823897911ad1 to your computer and use it in GitHub Desktop.
Full implementation
private var AssociatedKey: UInt = 0
private final class AssociatedObjectBox<T> {
let value: T
init(_ x: T) {
value = x
}
}
private func lift<T>(x: T) -> AssociatedObjectBox<T> {
return AssociatedObjectBox(x)
}
private func setAssociatedObject<T>(object: AnyObject, value: T, key: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
if let v: AnyObject = value as? AnyObject {
objc_setAssociatedObject(object, key, v, policy)
} else {
objc_setAssociatedObject(object, key, lift(value), policy)
}
}
private func getAssociatedObject<T>(object: AnyObject, key: UnsafePointer<Void>) -> T? {
if let v = objc_getAssociatedObject(object, key) as? T {
return v
} else if let v = objc_getAssociatedObject(object, key) as? AssociatedObjectBox<T> {
return v.value
} else {
return nil
}
}
public final class MyViewController: UIViewController {
// Your implementation
}
extension MyViewController: ViewModelBindable {
public func bindViewModel(viewModel: MyViewModel) {
// binding logic
}
}
public protocol ViewModelBindable: class {
typealias ViewModel
var viewModel: ViewModel? { get set }
func bindViewModel(viewModel: ViewModel)
func unbindViewModel(viewModel: ViewModel)
func shouldBindViewModel() -> Bool
}
extension ViewModelBindable where Self: AnyObject {
public var viewModel: ViewModel? {
get {
return getAssociatedObject(self, key: &AssociatedKey)
}
set(newViewModel) {
if let viewModel = newViewModel {
setAssociatedObject(self, value: viewModel, key:
&AssociatedKey, policy:
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if shouldBindViewModel() {
registerBinding(viewModel)
}
}
}
}
private func registerUnbinding(viewModel: ViewModel) {
unbindViewModel(viewModel)
}
private func registerBinding(viewModel: ViewModel) {
bindViewModel(viewModel)
}
}
@davidlondono
Copy link

I have problems implementing it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment