1

I'm getting an error: Generic parameter 'B' could not be inferred when trying to do a Bond bidirectionalBind with a non optional string and a UITextField. With a optional string it works fine.

Below is some example Swift Code that demonstrates this error.

protocol ItemModel {
    var _id: Observable<String> { get set }
    var title: Observable<String?> { get set }
}

class Item: NSObject, ItemModel {
    var _id: Observable<String> = Observable<String>("")
    var title: Observable<String?> = Observable<String?>(nil)
}

class MyViewModel {
    var pendingItem: Item? = Item()
}

class MyViewController: UIViewController {
    private var viewModel: MyViewModel = MyViewModel()

    @IBOutlet var id: UITextField!
    @IBOutlet var titleField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.pendingItem?._id.bidirectionalBind(to: id.reactive.text) // fails with error: Generic parameter 'B' could not be inferred
        viewModel.pendingItem?.title.bidirectionalBind(to: titleField.reactive.text)
    }
}

The problem is when trying to setup the bidirectionalBind to the _id it fails with the following error:

Generic parameter 'B' could not be inferred

Everything is exactly the same between the _id and title except for the fact that the title is optional while the _id is not. That is the only thing I can figure out why it's failing.

Therefor I think the question is, how can I do a bidirectionalBind in Bond to a UITextField on a non optional string variable? But more generally, how can I fix this error?


Some other information. Just from a usability standpoint, if id.text is nil which means the UITextField is empty, I'd like it to just default to an empty string. I know that I can't set it to nil because _id is not optional. So setting the default value in case it is nil to an empty string is completely fine by me.

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
  • 2
    I'm not familiar with Bond, however a bidirectional bind would mean that the text field will also update the property, and you cannot send an optional to a non-optional property. Maybe try an unidirectional bind? – Cristik Sep 21 '18 at 20:11
  • @Cristik There are certain reasons I want a bidirectional bind in this case. For example later on there will be this part where I edit the value in code and need that to be reflected to the user. – Charlie Fish Sep 21 '18 at 20:16
  • 1
    Then you can either change the `_id` to hold a `String?`, or add a new observable to `UITextField` that maps over a non-optional string, whichever feels more comfortable. – Cristik Sep 21 '18 at 20:18

0 Answers0