ios – 使用MVVM时,如何在子ViewControllers中扩展ViewModel?

我有这种层次结构:

class OneViewModel {
}

class OneViewController {
  var viewModel = OneViewModel()
}

class TwoViewModel : OneViewModel {
}

class TwoViewController : OneViewController {
  var viewModel = TwoViewModel() // ???
}

我知道在Swift中不允许覆盖属性类型,但是对于子ViewController携带两个ViewModel没有意义,怎么会解决这个问题呢?谢谢!

最佳答案 我用这个:

class OneViewController {
  var viewModel: OneViewModel {
    return storedViewModel
  }
  lazy var storedViewModel: OneViewModel = {
    type(of: self).viewModelProvider()
  }()
  class func viewModelProvider() -> OneViewModel {
    return OneViewModel()
  }
}

class TwoViewController {
  override var viewModel: TwoViewModel {
    return storedViewModel as! TwoViewModel
  }
  override class func viewModelProvider() -> OneViewModel {
    return TwoViewModel()
  }
}

设置有点冗长,但之后使用起来既简单又清晰.

点赞