简体   繁体   中英

Swift call a method after 2 bool didset call

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()
    }
}
var canDo: Bool {
    didSet {
        if isView{
            reload()
        }

    }
}

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

    }
}

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()
}

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()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM