RXSwift绑定返回意外地发现零,而解包一个可选的值

我是MVVM和RxSwift的初学者,我想在我的下一个项目中实现它。 目前,我正在处理我的login模块,一切都看起来不错,但每次运行我的应用程序时,它会触发一个错误时绑定文本字段到我的ViewModel说“意外地发现零,而解包可选值”。

有人能帮我摆脱它吗? 以下是我如何做到的:

class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! private var loginViewModel: UserLoginViewModel! private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() emailTextField.rx.text.orEmpty .bind(to: loginViewModel.emailAdd) .disposed(by: disposeBag) <---- Displays "Unexpectedly found nil while unwrapping an Optional value" passwordTextField.rx.text.orEmpty .bind(to: loginViewModel.password) .disposed(by: disposeBag) <---- Displays "Unexpectedly found nil while unwrapping an Optional value" } } /////loginProtocol protocol loginProtocol { //MARK - Input var emailAdd: Variable<String> { get } var password: Variable<String> { get } var loginButtonDidTap:PublishSubject<Void>{ get } var loginActionResult: Driver<AutenticationStatus> { get } } /// VIEW MODEL class UserLoginViewModel: loginProtocol { var emailAdd: Variable<String> var password: Variable<String> let loginButtonDidTap = PublishSubject<Void>() var loginActionResult:Driver<AutenticationStatus> init(apiService: API) { let emailV = Variable<String>("") let passwordV = Variable<String>("") emailAdd = emailV password = passwordV let usernameAndPassword = Observable.combineLatest(emailAdd.asObservable(), password.asObservable()) { ($0, $1) } loginActionResult = loginButtonDidTap.asObservable() .withLatestFrom(usernameAndPassword) .flatMapLatest { (emailAdd, password) in return apiService.login(email: emailAdd, password: password) }.asDriver(onErrorJustReturn:.error(.server)) } } 

这是截图

谢谢。

在你的代码中,网点或ViewModel可能是零。 如果你的代码部分是完整的, loginViewModel永远不会被创build。

 override func viewDidLoad() { super.viewDidLoad() // create view model loginViewModel = UserLoginViewModel(apiService: /* your api service */) emailTextField.rx.text.orEmpty .bind(to: loginViewModel.emailAdd) .disposed(by: disposeBag) passwordTextField.rx.text.orEmpty .bind(to: loginViewModel.password) .disposed(by: disposeBag) }