我在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
}
我想知道将此支票插入班级的位置。
简单的解决方案:使用可选的参数类型声明(必填)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)