Created
June 6, 2020 16:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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