1

我收到一个错误:尝试Generic parameter 'B' could not be inferred使用非可选字符串和. 使用可选字符串可以正常工作。 bidirectionalBindUITextField

下面是一些演示此错误的示例 Swift 代码。

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)
    }
}

问题是在尝试设置bidirectionalBind_id时失败并出现以下错误:

无法推断通用参数“B”

除了 the是可选的而 the不是之外,在_idand之间的一切都完全相同。这是我唯一能弄清楚它为什么失败的原因。titletitle_id

因此,我认为问题是,如何bidirectionalBind在非可选字符串变量上对 UITextField 进行绑定?但更一般地说,我该如何解决这个错误?


其他一些信息。仅从可用性的角度来看,如果id.textnil这意味着 UITextField 为空,我希望它默认为空字符串。我知道我无法将其设置为,nil因为_id它不是可选的。因此,将默认值设置为nil空字符串对我来说完全没问题。

4

0 回答 0