Search code examples
swiftrx-swift

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?


Solution

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