Dynamically setting willSet & didSet in Swift

I see the potential use willSetand didSetreplacement parts KVO type of code that I have used in Objective-C. One of the benefits of Objective-C is dynamism, especially the ability to create runtime behavior. To willSetand didSetwere helpful to me, I need to be able to dynamically assign their behavior. Is it possible to establish their "content" or the behavior that they embody dynamically? One use case would be to attach model properties to a view. In pseudo code:

mvvm = new MVVM(packageModel, 'url', packageView, 'urlLabel')
class MVVM {
  init(model: Model, modelPropertyName : NSString, view: View, viewPropertyName : NSString) {
    model.propertyDescriptor('willSet', modelPropertyName, (newUrl){
      view[viewPropertyName].text = newUrl
    })
  }
}
+4
source share
1 answer

How about something like this:

println("begin")

import Swift


class Observable<T> {
    typealias ChangeNotifier = (T) -> ()

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

    var value:T { didSet {
        for n in notifiers {
            n(self.value)
        }
    }}

    func subscribe(notifier:ChangeNotifier) {
        notifiers.append(notifier)
    }

    private var notifiers: [ChangeNotifier] = []

}



class ViewModel {
    var numberOfSheep:Observable<Int> = Observable<Int>(t:1)
}

class ViewController {
    var viewModel:ViewModel? = nil { didSet {
        viewModel?.numberOfSheep.subscribe(){ t in
            println("value is now \(t)")
        }}}
}

var vc = ViewController()
var vm = ViewModel()
vc.viewModel = vm

vm.numberOfSheep.value = 2
vm.numberOfSheep.value = 3


println("end")

ModelObserver: "func __conversion() → T", , . , . ++, - .

+3

All Articles