-3

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.

ZGski
  • 2,398
  • 1
  • 21
  • 34
Blue
  • 1,408
  • 4
  • 17
  • 36
  • It will never be nil so what is there to check? – matt Dec 10 '19 at 21:21
  • Are you saying that you'd like a method that takes an Optional and sets it only if it's non-nil? – creeperspeak Dec 10 '19 at 21:23
  • @Wizard Basic questions are welcome, but only if accompanied with some kind of evidence that suggests that OP tried to do their own background research before posting. – Alexander Dec 10 '19 at 21:40

1 Answers1

2

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)
vadian
  • 274,689
  • 30
  • 353
  • 361