Swift 将闭包从ViewController移动到ViewModel

Swift 将闭包从ViewController移动到ViewModel,swift,mvvm,closures,Swift,Mvvm,Closures,以下截取的代码位于mySettingViewController中,需要将LocationManager.LocationUpdate关闭逻辑移到SettingsViewModel中。我被困在如何管理它 设置查看控制器.swift private let settingsViewModel : SettingsViewModel() func updateLocationButtonClicked() { if isLocationUpdateNeeded() { Custom

以下截取的代码位于my
SettingViewController
中,需要将
LocationManager.LocationUpdate
关闭逻辑移到
SettingsViewModel
中。我被困在如何管理它

设置查看控制器.swift

private let settingsViewModel : SettingsViewModel()

func updateLocationButtonClicked() {
 if isLocationUpdateNeeded() {
       CustomLocationManager.locationUpdated { success in
         if success {
           self.updateMap()
         } else {
           DispatchQueue.main.async {
             // add an alertview here
           }
         }
       }
     } else {
        updateMap()
     }
 }

有很多方法可以实现它

可以将函数属性添加到viewModel:

var locationUpdateDidSucceed: (() -> Void)?
var locationUpdateDidFail: (() -> Void)?
CustomLocationManager.locationUpdated { [weak self] success in
    if success {
       self?.locationUpdateDidSucceed?()
    } else {
       self?.locationUpdateDidFail?()
    }
}
然后,您可以在VC中绑定这些方法:

settingsViewModel.locationUpdateDidSucceed = { [weak self] in
    self?.updateMap()
}

settingsViewModel.locationUpdateDidFail = { [weak self] in
    self?.displayAlert()
}
最后,将逻辑添加到viewModel:

var locationUpdateDidSucceed: (() -> Void)?
var locationUpdateDidFail: (() -> Void)?
CustomLocationManager.locationUpdated { [weak self] success in
    if success {
       self?.locationUpdateDidSucceed?()
    } else {
       self?.locationUpdateDidFail?()
    }
}

那么
updateMap()
方法呢?