Swift call a method after 2 bool didset call

221 Views Asked by At

I have 2 bool with a didset method. Inside both didset it called a same method. So I want to call a method after that 2 bool did sets called

var canDo: Bool {
    didSet {
        reload()
    }
}

var isView: Bool {
    didSet {
        reload()
    }
}
3

There are 3 best solutions below

0
Sandeep Maurya On BEST ANSWER
var canDo: Bool {
    didSet {
        if isView{
            reload()
        }

    }
}

var isView: Bool {
    didSet {
        if canDo{
            reload()
        }

    }
}
2
Razi Tiwana On

We can achieve this with the help of Optionals

Now when update your code like

var canDo: Bool? {
    didSet {
        if isView != nil {
         reload()
        }
    }
}

var isView: Bool? {
    didSet {
        if canDo != nil {
         reload()
        }
    }
}

EDIT

If you meant set as in true then simply ignore the above and add

var canDo: Bool {
    didSet {
        if isView {
         reload()
        }
    }
}

var isView: Bool {
    didSet {
        if canDo {
         reload()
        }
    }
}
0
Daniel Storm On

I'd suggest a new function to handle the logic for when to call reload() rather than having the logic in both didSet's. This way if new logic needs to be added it can be added in one place:

var canDo: Bool {
    didSet { maybeReload() }
}

var isView: Bool {
    didSet { maybeReload() }
}

private func maybeReload() {
    guard
        canDo,
        isView
        else { return }

    reload()
}