-3

我在 Swift 中有一堂课:

class myClass {
    var theBool : Bool

    init(theBool: Bool) {
        self.theBool = theBool
    }

    init() {
        self.theBool = false
    }

}

在我的代码的其他地方,我有这个检查:

classist  = myClass()

if let daBool = someRandomBool {
    classist.theBool = daBool
}

我想知道在哪里将此支票插入班级。

4

1 回答 1

2

简单的解决方案:使用可选参数类型声明(必需)init方法并在那里执行检查

class MyClass {
    var theBool : Bool

    init(bool: Bool?) {
        self.theBool = bool ?? false
    }
}

let someRandomBool : Bool? = true
let classist = MyClass(bool: someRandomBool)

或者 - 有点不同但仍然更简单 - 使用结构

struct MyStruct {
    var theBool : Bool
}

let someRandomBool : Bool? = true
let classist = MyStruct(theBool: someRandomBool ?? false)
于 2019-12-10T21:27:16.977 回答