Cannot use instance member 'model' within property initializer; property initializers run before 'self' is available

class SampleViewModel {
     
  var model: SampleModel?
  let changeData = Observer(model?.head) //Line error
   
  init() {
    self.model = SampleModel()
     
  }
  
  func changeLabel(_ tf: String) {
     
    self.changeData.value = tf
  }
   
}
final class Observer<T> {
   
   init(_ value: T) {
   self.value = value
  }
  
  typealias Listener = (T) -> Void

  var listener: Listener?

  var value: T {
    didSet(oldVal) {

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

    listener?(value)
  }
}
struct SampleModel {
   
   var head = "initValue"
  
}
 
// I want access to SampleMoel's 'head' at ViewModel
// How to fix this error? 
// this is MVVM(not Use combine, RxSwift ... only use Uikit)

As the error message is clearly stating, you cannot use any instance members within property initializer (= Observer(model?.head)).

One way to work around this restriction would be moving initialization into init().

class SampleViewModel {
    var model: SampleModel?
    let changeData: Observer<String>
    
    init() {
        let model = SampleModel()
        self.model = model
        self.changeData = Observer(model.head)
    }
    
    func changeLabel(_ tf: String) {
        self.changeData.value = tf
    }
}

You will not see the error with this change, but I'm not sure this would work as you expect.

Cannot use instance member 'model' within property initializer; property initializers run before 'self' is available
 
 
Q