Skip to content

Instantly share code, notes, and snippets.

@tarunon
Last active January 6, 2017 08:13
Show Gist options
  • Save tarunon/fc544e3fd9e73168ec24fcd1ef58f94c to your computer and use it in GitHub Desktop.
Save tarunon/fc544e3fd9e73168ec24fcd1ef58f94c to your computer and use it in GitHub Desktop.
Generics ViewModel
//: Playground - noun: a place where people can play
import UIKit
protocol ViewModelType {
associatedtype ViewType
associatedtype ModelType
var base: ModelType { get }
var fields: [String: Any] { get set }
}
extension ViewModelType {
func get<T>(key: String = #function, defaultValue: T) -> T {
return (fields[key] as? T) ?? defaultValue
}
mutating func set<T>(key: String = #function, newValue: T) {
fields[key] = newValue
}
}
struct ViewModel<View, Model>: ViewModelType {
typealias ViewType = View
typealias ModelType = Model
let base: Model
var fields: [String: Any] = [:]
init(_ base: Model) {
self.base = base
}
}
protocol ModelType {
func at<V>(_ viewType: V.Type) -> ViewModel<V, Self>
}
extension ModelType {
func at<V>(_ viewType: V.Type) -> ViewModel<V, Self> {
return ViewModel(self)
}
}
struct YourModel: ModelType {
let text: String?
}
extension ViewModelType where ViewType: UITextView, ModelType == YourModel {
var text: String {
return base.text ?? ""
}
var hidden: Bool {
set {
set(newValue: newValue)
}
get {
return get(defaultValue: false)
}
}
}
var vm = YourModel(text: "test").at(UITextView.self)
vm.text
vm.hidden
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment