Skip to content

Instantly share code, notes, and snippets.

@erikolsson
Created February 14, 2017 16:43
Show Gist options
  • Save erikolsson/b27bf97041367deec27dc507996ba3fc to your computer and use it in GitHub Desktop.
Save erikolsson/b27bf97041367deec27dc507996ba3fc to your computer and use it in GitHub Desktop.
protocol ViewModelType {
associatedtype Model
associatedtype Input
init(model: Model, input: Input)
}
class ViewModel: ViewModelType {
let model: Model
required init(model: Model, input: Input) {
self.model = model
}
struct Model {
let userId: String
}
struct Input {
//let buttonTap: Observable<Void>
}
}
enum Bindable<T: ViewModelType> {
case unbound(model: T.Model)
case bound(model: T.Model, viewModel: T)
mutating func bind(input: T.Input) -> T {
switch self {
case let .unbound(model), let .bound(model, _): // <- using the same name for both values of a generic type
let viewModel = T(model: model, input: input) // <- EXC_BAD_ACCESS here prior to Swift 3.1
self = .bound(model: model, viewModel: viewModel)
return viewModel
}
}
}
let input = ViewModel.Input()
let model = ViewModel.Model(userId: "123")
var b: Bindable<ViewModel> = .unbound(model: model)
let viewModel = b.bind(input: input)
print(viewModel.model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment