如何执行无类别检查

问题描述 投票:-2回答:1

我在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
}

我想知道将此支票插入班级的位置。

swift swift-class
1个回答
1
投票

简单的解决方案:使用可选的参数类型声明(必填)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)
© www.soinside.com 2019 - 2024. All rights reserved.