How to perform class nil checks

63 Views Asked by At

I have a class in Swift:

class myClass {
    var theBool : Bool

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

    init() {
        self.theBool = false
    }

}

Elsewhere in my code, I have this check:

classist  = myClass()

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

I want to know where to insert this check into the Class.

1

There are 1 best solutions below

0
On BEST ANSWER

Simple solution: Declare the (required) init method with an optional parameter type and perform the check there

class MyClass {
    var theBool : Bool

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

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

or – a bit different but still simpler – with a struct

struct MyStruct {
    var theBool : Bool
}

let someRandomBool : Bool? = true
let classist = MyStruct(theBool: someRandomBool ?? false)