swift - 拒绝从类内部但函数内部的任何地方编辑属性

标签 swift

除了函数之外,有什么方法可以限制在类内部设置属性吗?这是说明问题的代码:

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/

相关文章:

ios - 如何通过调试跳转controller

ios - 从 Firebase 设置用户值

ios - 将项目转换到两个选项之一

xcode - 如何在 Xcode 中使用加号 (+) 导入 Swift 模块

ios - swift iOS : How do I make an Instagram link?

ios - 为 AVPlayer 更新时 UISlider 跳转

ios - 如何在 Swift 中将图像转换为渐进式 JPEG?

ios - 在 Realm 中,当我更新它时,它只在第 0 个索引中更新如何解决它?

ios - '&' used with non-inout argument of type ' AutoreleasingUnsafeMutablePointer<UIImage?>'

ios - iOS 中的不同背景模式