【发布时间】:2020-06-18 05:10:34
【问题描述】:
谁能解释为什么我可以将值设置为 get-only 属性?
这是一个例子。此协议包含自定义类类型的 get-only 属性,以及符合它的类。
protocol ViewModel {
var title: MyTitle { get }
}
class MyTitle {
var title: String
var otherProperty: Int
}
class MyViewModel: ViewModel {
var title: MyTitle
init() {
self.title = MyTitle.init()
}
func didChangeTitle(title: String) {
self.title.title = title
}
}
我认为title属性应该是get-only,当用户编辑完UITextView时会触发MyViewModel中的函数。
class TableViewCell: UITableViewCell, UITextViewDelegate {
var viewModel: MyViewModel?
func bind(to viewModel: MyViewModel) {
self.viewModel = viewModel
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
self.viewModel?.title.title = textView.text /* Why can the property supposed to be get-only be changed here */
textView.resignFirstResponder()
return false
}
return true
}
}
但实际上我可以不用MyViewModel的功能直接更新值。
谁能解释一下?
【问题讨论】:
-
你实际上并没有改变
self.viewModel?.title。你正在改变self.viewModel?.title.title。更改类的属性不算作“更改类”。 -
请注意,协议是要求而非限制。你可以设置 MyTitle 属性,只要它没有被声明为常量
-
@LeoDabus 所以如果我不想直接更改
MyTitle的title,我应该将其声明为private类型,对吧? -
private不允许从该类进行任何类型的访问。如果您想限制仅设置其值,请使用private (set) -
@LeoDabus 知道了!谢谢。