Blue
Blue

Reputation: 1448

How to perform class nil checks

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.

Upvotes: -3

Views: 53

Answers (1)

vadian
vadian

Reputation: 285064

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)

Upvotes: 2

Related Questions