Swift mutable structs in closure of class and struct behave differently

后端 未结 3 940
攒了一身酷
攒了一身酷 2021-02-05 18:02

I have a class(A) that has a struct variable (S). In one function of this class I call a mutating function on struct variable,this function takes a closure. Body of this closure

3条回答
  •  花落未央
    2021-02-05 18:42

    How about this?

    import Foundation
    import XCPlayground
    
    
    protocol ViewModel {
      var delegate: ViewModelDelegate? { get set }
    }
    
    protocol ViewModelDelegate {
      func viewModelDidUpdated(model: ViewModel)
    }
    
    struct ViewModelStruct: ViewModel {
      var data: Int = 0
      var delegate: ViewModelDelegate?
    
      init() {
      }
    
      mutating func fetchData() {
        XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
        NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://stackoverflow.com")!) {
           result in
          self.data = 20
          self.delegate?.viewModelDidUpdated(self)
          print("viewModel.data in fetchResponse : \(self.data)")
    
          XCPlaygroundPage.currentPage.finishExecution()
          }.resume()
      }
    }
    
    protocol ViewModeling {
      associatedtype Type
      var viewModel: Type { get }
    }
    
    typealias ViewModelProvide = protocol
    
    class ViewController: ViewModelProvide {
      var viewModel = ViewModelStruct() {
        didSet {
          viewModel.delegate = self
          print("ViewModel in didSet \(viewModel)")
        }
      }
    
      func viewDidLoad() {
        viewModel = ViewModelStruct()
      }
    
      func changeViewModelStruct() {
        print(viewModel)
        viewModel.fetchData()
      }
    }
    
    extension ViewModelDelegate where Self: ViewController {
      func viewModelDidUpdated(viewModel: ViewModel) {
        self.viewModel = viewModel as! ViewModelStruct
      }
    }
    
    var c = ViewController()
    c.viewDidLoad()
    c.changeViewModelStruct()
    

    In your solution 2, 3, it need to assign new View Model in ViewController. So I wanna make it automatically by using Protocol Extension. didSet observer works well! But this need to remove force casting in delegate method.

提交回复
热议问题