Skip to content

Instantly share code, notes, and snippets.

@hmhmsh
Last active January 20, 2018 13:31
Show Gist options
  • Save hmhmsh/d660a83e01d9d2c6e7a7d9a2ea4a098c to your computer and use it in GitHub Desktop.
Save hmhmsh/d660a83e01d9d2c6e7a7d9a2ea4a098c to your computer and use it in GitHub Desktop.
MVVMを2パターン考えてみる(追記:MVPでしたすみません) ref: https://qiita.com/hmhmsh/items/263f1f531c220eb781ee
struct Entity {
let name: String
let age: Int
}
struct Model {
let name: String
let age: Int
}
extension MVVMViewController: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.getModelCount()
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "MVVMCell", for: indexPath)
cell.textLabel?.text = viewModel.getName(index: indexPath.row)
return cell
}
}
protocol RepositoryToViewModel: class {
func onGetModels(models: [Model])
}
class Repository {
weak var viewModel: RepositoryToViewModel?
func getModels() {
// 通信などで取得する
// 今回は仮で作成
var models = [Model]()
models.append(Model(name: "tarou", age: 25))
models.append(Model(name: "zirou", age: 20))
models.append(Model(name: "saburou", age: 18))
viewModel?.onGetModels(models: models)
}
}
class ViewModel {
private var models: [Model] = [] {
didSet {
view?.onChangeModels()
}
}
/* 省略 */
func getModelCount() -> Int {
return models.count
}
func getName(index: Int) -> String {
return models[index].name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment