除了函数之外,有什么方法可以限制在类内部设置属性吗?这是说明问题的代码:
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())
}
}
最佳答案
我不相信有任何语言机制可以让你做到这一点。您可以将 private
用于其他不使用它的类。
如果您非常在意,您可以为该属性制作一个包装类,但我认为这比它的值(value)更麻烦。
通常这是使属性命名为 _property
的好地方,以表明它是私有(private)的或在上面添加注释。
关于swift - 拒绝从类内部但函数内部的任何地方编辑属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43391252/