0

In working through the tutorial at https://www.raywenderlich.com/138547/getting-started-with-rxswift-and-rxcocoa

using Xcode 9.3 and Swift4

There is the code:

private func setupTextChangeHandling() {
  let creditCardValid = creditCardNumberTextField
    .rx
    .text //1
    .throttle(throttleInterval, scheduler: MainScheduler.instance) //2
    .map { self.validate(cardText: $0) } //3

  creditCardValid
    .subscribe(onNext: { self.creditCardNumberTextField.valid = $0 }) //4
    .addDisposableTo(disposeBag) //5
} 

This is giving an error on the map() call on the $0 parameter:

Cannot convert value of type 'String?' to expected argument type 'String'

func validate(cardText: String) -> Bool

Is the declaration of the called function inside the map closure.

In looking at the Apple docs, the map (optional) should pass an unwrapped variable in as the parameter so $0 should already be unwrapped and I don't see any notes on it being deprecated or changed.

Not quite sure what is wrong here.

TIA

christopher.online
  • 2,614
  • 3
  • 28
  • 52
chadbag
  • 1,837
  • 2
  • 20
  • 34

1 Answers1

0

RxSwift's map won't unwrap for you (neither does Swift's btw; you can remove nils from an array with compactMap).

RxSwift has a nice little convenience operator that allows to convert nil to an empty string and avoid the optional: textField.rx.text.orEmpty

Side note: addDisposableTo is deprecated; you should use disposed(by:)

Valérian
  • 1,068
  • 8
  • 10
  • Actually, Swift has two map() functions, one for Arrays and one for optionals and the Apple docs say it will unwrap it for you: https://developer.apple.com/documentation/swift/optional/1539476-map – chadbag Jul 12 '18 at 18:45