Skip to content

Instantly share code, notes, and snippets.

@smosko
Created June 6, 2020 16:49
Show Gist options
  • Save smosko/3dfac2592ef8ca6ae3d5a03bdec96ee2 to your computer and use it in GitHub Desktop.
Save smosko/3dfac2592ef8ca6ae3d5a03bdec96ee2 to your computer and use it in GitHub Desktop.
Base ViewModel using dynamic member lookup to access object properties and property publishers
import Combine
import Foundation
@dynamicMemberLookup
public class ViewModel<Object> {
private var object: Object
init(_ object: Object) {
self.object = object
}
public subscript<T>(dynamicMember keyPath: WritableKeyPath<Object, T>) -> T {
get { object[keyPath: keyPath] }
set { object[keyPath: keyPath] = newValue }
}
}
extension ViewModel where Object: NSObject {
public var publishers: Publishers<Object> {
Publishers(object)
}
@dynamicMemberLookup
public struct Publishers<Object: NSObject> {
private let object: Object
public init(_ object: Object) {
self.object = object
}
public subscript<T>(dynamicMember keyPath: KeyPath<Object, T>) -> AnyPublisher<T, Never> {
object.publisher(for: keyPath).eraseToAnyPublisher()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment