我正在尝试使用泛型简化以下代码。我可以使用泛型实现相同的功能,而不是对ChildViewOne,ChildViewTwo和ChildViewThree中的每个类型进行有条件的展开?

struct UserInfo {
  let name: String
  let image: UIImage
}

enum SomeType {
  case typeOne
  case typeTwo
  case typeThree
}

struct ParentViewModel {
   let userInfo: UserInfo
   let type: SomeType

   var contentViewModel: Any {
    switch type {
      case .typeOne:
           return ChildViewModelOne(name: userInfo.name, type: type)
      case .typeTwo:
           return ChildViewModelTwo(image: userInfo.image, type: type)
      case .typeThree:
           return ChildViewModelThree(image: userInfo.image)
   }
}

struct ChildViewModelOne {
  let name: String
  let type: SomeType
}

struct ChildViewModelTwo {
  let image: UIImage
  let type: SomeType
}

struct ChildViewModelThree {
  let image: UIImage
}

ParentViewController将与ParentViewModel一起注入。
class ParentViewController: UIViewController {
  let viewModel: ParentViewModel

  init(viewModel: ParentViewModel) {
    self.viewModel = viewModel
    super.init(bundle: nil, frame: nil)
  }

  // other required initializer

  func configureViewForType() {
     // Logic to handle subviews - ChildViewOne, ChildViewTwo & ChildViewThree
  }
}

这是我到目前为止尝试过的:
我介绍了一个协议ConfigurableView
protocol ConfigurableView {
    associatedtype ViewModel
    func configure(model: ViewModel)
}

class ChildViewOne: UIView, ConfigurableView {
    func configure(model: ChildViewModelOne) {

    }

    typealias ViewModel = ChildViewModelOne
}

更新

如何从ParentViewModel将此返回为ParentViewModel中的contentViewModel对象?从contentViewModel内的func configureViewForType()调用ParentViewController,其中基于ParentViewModel内的type值,我加载了正确的ChildView
有没有更好的方法来实现这一目标?

最佳答案

视图模型实际上不是“ViewModel”。这个想法无处不在,因为并非所有语言都具有嵌套类型。相反,它是View.Model

class ChildViewOne: UIView {
  struct Model {
    let name: String
  }

  init?(model: Model, coder: NSCoder) {
    self.model = model
    super.init(coder: coder)
  }

  private let model: Model

  required init?(coder _: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

07-24 09:51