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
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.