ios - Swift 中的泛型和 ViewModel

标签 ios swift generics

我正在尝试使用泛型简化以下代码。除了对 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 将被注入(inject) 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
  }
}

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

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

    }

    typealias ViewModel = ChildViewModelOne
}

更新

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

最佳答案

View 模型实际上不是“ View 模型”。这个想法很普遍,因为并非所有语言都有嵌套类型。相反,它是 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")
  }
}

关于ios - Swift 中的泛型和 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61719155/

相关文章:

ios - swift - Twilio 视频聊天 - 卡住时发出警报

ios - 无法使用 swift 从 json 访问嵌套字典/数组

swift - 通过 AVAudioRecorder 在 WatchOS 上录制音频

ios - 使用Firebase Phone身份验证时使应用程序崩溃

ios - 后台 UILocalNotification - iOS 9

c# - 如何在 C# 中创建将 DataRowCollection 转换为泛型对象数组的方法?

c# - 排序通用列表

C++ 模板性能包含模型和内联模型

ios - removeObserver with NSNotification...我做错了什么?

ios - 简单存储/检索 blob 或数据(可能是类的 NSKeyArchive)