除了函数之外,还有什么方法可以限制类中设置的属性吗?下面是说明问题的代码:
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())
}
}发布于 2017-04-13 12:03:15
我不相信有任何语言技工允许你这样做。您可以将private用于其他类,而不是使用它。
如果您非常关心这个属性,那么您可以为该属性创建一个包装类,但我相信这比它的价值更麻烦。
通常,这是一个很好的地方,可以让名为_property的属性表示它是私有的,或者添加上面的注释。
https://stackoverflow.com/questions/43391252
复制相似问题