hoang Cap
hoang Cap

Reputation: 804

RxSwift - Construct the Observable using function inside transform function

Here's my code snippet:

open class SomeClass {
  let driver: Driver<Bool>
  init(input: Observable<String>) {
    driver = input
      .map( { s -> Bool in self.convert(text: s) }) // error 'self' captured by a closure before all members were initialized
    .asDriver(onErrorJustReturn: false)
  }

  func convert(text: String) -> Bool {
    // Do some complex calculation
    return true
  }
}

Explanation: In my SomeClass, I have a driver object of type Driver<Bool>, then inside my init, I'll take an Observable<String> and map it to a Observable<Bool>. However in order to do the conversion I need to call the func convert() inside the mapping closure, thus I'm getting the error

'self' captured by a closure before all members were initialized

Can someone please show me how to get through this?

Upvotes: 2

Views: 390

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

The simplest solution is to move convert out of the class:

open class SomeClass {
  let driver: Driver<Bool>
  init(input: Observable<String>) {
    driver = input
      .map( { s -> Bool in convert(text: s) }) // error 'self' captured by a closure before all members were initialized
    .asDriver(onErrorJustReturn: false)
  }

}

func convert(text: String) -> Bool {
  // Do some complex calculation
  return true
}

You should probably make convert(text:) private to avoid name pollution.

Upvotes: 1

Related Questions