Reputation: 39
Can anyone explain why I can set value to a get-only property?
Here is the example. This protocol contains get-only property of type the custom class, and a class conform to it.
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
}
}
I think the title
property should be get-only, and will trigger function in MyViewModel when user finish editing UITextView
.
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
}
}
But actually I can update the value directly without the function of MyViewModel.
Can anyone explain?
Upvotes: 0
Views: 559
Reputation: 76
You are not actually declaring a get-only
property by conforming a protocol. You can use computed property, and declare it by
var title: String {
return "Something"
}
And furthermore, you are changing a property inside a class, not that class itself
EDIT
Or as proposed in the comments you can define a private setter
private (set) var title: String
Upvotes: 1