在不同类型的 RxSwift 中绑定文本字段的两种方式

Two ways binding textfiled in RxSwift in different type

我正在为 UITextField 扩展创建两种绑定方式。它适用于字符串。但为什么不是 Int 呢? 这是我的分机:

import Foundation
import RxCocoa
import RxSwift

extension UITextField {
    func bind(with property: BehaviorRelay<String?>, bag: DisposeBag = DisposeBag()) {
        property.bind(to: self.rx.text).disposed(by: bag)
        self.rx.text.bind(to: property).disposed(by: bag)
    }

    func bind(with property: BehaviorRelay<Int?>, bag: DisposeBag = DisposeBag()) {
        property.map { intValue in
            return Int.toString(intValue) //convert from Int to String
        }.bind(to: self.rx.text).disposed(by: bag)
        self.rx.text.orEmpty.map { text in
            return String.toInt(text) ?? 0 //convert from String to Int
        }.bind(to: property).disposed(by: bag)
    }
}

在我的视图模型中:

let fullName = BehaviorRelay<String?>(value: nil)
let phone = BehaviorRelay<Int?>(value: nil)

用法:

textField1.bind(with: viewModel.fullName) //working well
textField2.bind(with: viewModel.phone) //only from viewModel to textField

但是当我直接使用时它是这样工作的:

textField2.rx.text.map { text in
    return String.toInt(text) ?? 0
}.bind(to: viewModel.phone).disposed(by: bag)

我错过了什么吗? 任何答案都很受欢迎。谢谢

我在调用该函数时缺少传递 bag。准确地说,应该是:

let bag = DisposeBag()
textField1.bind(with: viewModel.fullName, bag: bag) //working well
textField2.bind(with: viewModel.phone, bag: bag)

我还需要删除默认值以避免将来忘记

func bind(with property: BehaviorRelay<Int?>, bag: DisposeBag) {
        property.map { intValue in
            return Int.toString(intValue) //convert from Int to String
        }.bind(to: self.rx.text).disposed(by: bag)
        self.rx.text.orEmpty.map { text in
            return String.toInt(text) ?? 0 //convert from String to Int
        }.bind(to: property).disposed(by: bag)
    }