简体   繁体   中英

ViewModel calls ViewController method MVVM pattern without creating delegate, Swift

I am using MVVM design pattern and when currentStatus property gets updated then I would like to call SettingsViewController method.

Is there a way to make it happen without creating delegate or other better approach?

SettingsModel.swift

var currentStatus: String? {
    get {
      return UserDefaults.standard.string(forKey: KeyValuePair.selectedStatus)
    }
    set {
      UserDefaults.standard.set(newValue, forKey: KeyValuePair.selectedStatus)
      updateStatus()
    }
  }

SettingsModelViewController.swift

var settingVM : SettingsModel 

func updateStatus () {
}

If you don't want to use protocol inside the MVVM design pattern, I think creating a Box class and using generics would be nice.

For example,

Box.swift

class Box<T> {
  typealias Listener = T -> Void
  var listener: Listener?

  var value: T {
    didSet {
      listener?(value)
    }
  }

  init(_ value: T) {
    self.value = value
  }

  func bind(listener: Listener?) {
    self.listener = listener
    listener?(value)
  }
}

SettingsViewModel.swift

var yourPickerValue: Box<String?> = Box(nil)

SettingsModelVC.swift

private var yourUptatedValue: String
private var settingVM : SettingsModel()

settingVM.yourPickerValue.bind { [unowned self] in // or [weak self]
    self.yourUpdatedValue = $0
    UserDefaults.standard.string($0, forKey: KeyValuePair.selectedStatus)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM