在 Swift 中,有没有办法以编程方式添加我可以在整个 class 中使用而无需可选属性的子视图?

In Swift, is there a way to programmatically add subviews that I can use throughout my class without having optional attributes?

通常,当我使用自己的子视图创建自定义视图时,它往往看起来像这样:

class MyView : UIView {

    var myButton : UIButton?
    var myLabel  : UILabel?

    override init(frame: CGRect) {
        super.init(frame: frame)

        //Create the frames and such

        myButton = UIButton(frame: myButtonsFrame)
        myLabel  = UILabel(frame: myLabelsFrame)
    }

    // Do other things
}

这在技术上是可行的,但它似乎违反了 Swift 中可选的整个概念。因为我的子视图是 always 创建的,所以它们不应该有 ?s.

但是,因为它们确实存在,所以我经常被迫检查它们是否为 nil 或强制解包,即使我知道它们永远不应该是,如果是,它们应该会在 init 中失败。

有更好的方法吗?

是的,只需切换代码即可:

class MyView : UIView {

    var myButton : UIButton
    var myLabel  : UILabel

    override init(frame: CGRect) {
        myButton = UIButton(frame: myButtonsFrame)
        myLabel  = UILabel(frame: myLabelsFrame)

        super.init(frame: frame)
    }

    // Do other things
}

您只需确保在调用 super.init 之前初始化所有存储的属性。

或者,如果您 100% 确定在您第一次尝试访问任何 属性 或对它们起作用。

请注意,@tmpz 在评论中所说的是正确的 - 如果您不打算在之后更改它们的值,您可能希望使用 let 而不是 var 将属性声明为常量init 曾经。