首页 > 解决方案 > 使用可选类型协议有意义吗?

问题描述

我遇到了一个对我来说非常有趣的问题。可能你有更好的解释,我想分享和讨论一下。

protocol HomeViewModelProtocol {
    func getText(postCode: String?)
}

视图模型

HomeViewModel: HomeViewModelProtocol {
    func getText(postCode: String?) {
        guard let postCode = postCode else {
            return
        }
        postCode = someLocalVariable
    }

看法

 postCodeTextField.addTarget(self, action: #selector(postCodeFieldDidChange(_:)), for: .editingChanged)


@objc private func postCodeFieldDidChange(_ textField: UITextField) {
    viewModel.getText(postCode: textField.text)
}

我只是视图和视图模型。我想将可选类型传递给 viewmodel 因为我认为在视图模型中处理可选绑定会更好(视图不应该处理任何逻辑)对吗?

但我觉得这很奇怪,我以前从未见过这样的方法,可能我犯了一些错误,这就是为什么我想问如何getText根据 SOLID 来处理这种更有意义和更优雅的方法。

IMO 一切都很清楚,所以如果您认为需要调试详细信息,请在关闭问题之前尝试了解一点谢谢

标签: swift

解决方案


没有意义。text的属性UITextField——尽管被声明为可选——永远不会是零。你可以强制解开它

@objc private func postCodeFieldDidChange(_ textField: UITextField) {
    viewModel.getText(postCode: textField.text!)
}

或者在Exclamationmarkophobia的情况下使用 nil-coalescing 运算符

@objc private func postCodeFieldDidChange(_ textField: UITextField) {
    viewModel.getText(postCode: textField.text ?? "")
}

并声明您的协议方法是非可选的。

protocol HomeViewModelProtocol {
    func getText(postCode: String)
}

推荐阅读