2

I would like to create a Reactive extension to the UIButton which will take any object (value and reference type) and will enable the button based on the value. If it is nil I want to disable the button and enable if it there is value.

here is the code:

extension Reactive where Base: UIButton {
    var isEnabledForModel: Binder<Any?> {
        return Binder(base, binding: { 
            $0.isEnabled = $1 != nil
        })
    }
}

When I try to bind the observable which contains optional struct I get an error: Ambiguous reference to member 'bind(to: ). Is there any way to pass Any to the Binder or achieve it in different way? Maybe I want to make it too generic.

mikro098
  • 2,173
  • 2
  • 32
  • 48

1 Answers1

1

Yes, you are trying to make something that is too generic. For example, if you want the button disabled for a missing string, you probably also want it disabled for an empty string, but there is no way to express that in your binder.

That said, your code compiles fine for me. I suggest you clean your build folder and rebuild. Despite the fact that it compiles, the point of use becomes more complex than I think you would like.

let foo = Observable<Int?>.just(nil)
foo
    .map { $0 as Any? }
    .bind(to: button.rx.isEnabledForModel)
    .disposed(by: bag)

Note that you have to manually map the Int? into a Any?. If you remove the map you will get an error "Generic parameter 'Self' could not be inferred". Because it's a generic parameter, the system won't look for possible matches through the inheritance tree and therefore won't accept the isEnabledForModel.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72