Reputation: 1757
Is there any way to restrict property being set inside class from anywhere but function? Here is code to illustrate the problem:
import UIKit
class MyViewController: UIViewController {
var property: Int?
func setProperty(_ property: Int?, animated: Bool,
withColor color: UIColor,
andSomethingElse something: Any) {
// only allow property to be set here
self.property = property
// ...
}
override func viewDidLoad() {
super.viewDidLoad()
// What I'd like to achieve is deny following...
property = 42
// ...and somehow force to set value exclusively via function
setProperty(42,
animated: true,
withColor: .green,
andSomethingElse: LongCat())
}
}
Upvotes: 0
Views: 19
Reputation: 5195
I don't believe there is any language mechanic that allows you to do that. You could use private
for other classes not to use that.
If you care that much you can make a wrapper class for that property, but I believe this is more hassle than it is worth.
Usually this is a good place to make the property named like _property
to signal that it is private or add a comment above.
Upvotes: 1