swift - 使用可选类型协议有意义吗?
问题描述
我遇到了一个对我来说非常有趣的问题。可能你有更好的解释,我想分享和讨论一下。
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 一切都很清楚,所以如果您认为需要调试详细信息,请在关闭问题之前尝试了解一点谢谢
解决方案
没有意义。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)
}
推荐阅读
- magento - 添加折扣代码后如何在结帐 Magento 2 时强制更新/刷新运输方式(免费送货))
- java - 如何使用 nfc(android studio) 获取卡 ID
- primefaces - 如何使用 PrimeFaces 和 ChartJs 显示带时间戳的数据?
- javascript - 如何让主机和容器使用 Docker 读取/写入相同的文件?
- sql - 联合查询后消除重复的更好设计
- python - 使用python获取json对象值
- python-3.x - 尝试使用 Gensim 运行 Mallet 时出现 subprocess.CalledProcessError
- c# - 如何使用c#将动态查询插入表中
- php - 如何同时删除括号和括号内的文本以及之前的任何空格(如果存在)?
- c# - 如果 ON HEAP 和 OFF HEAP Memory full APACHE IGNITE 将条目逐出到磁盘