dimanche 8 novembre 2020

Swift builder pattern where order matters

So I would like to create a builder where the order matters. However, I don't want to concern the caller with what that order is.

class myClass {
    private var a: Bool
    private var b: Bool
    private var c: Bool
    init() {
        a = false
        b = false
        c = false
    }
    func build() { // enforces order
        if a {
            // build a
        }
        if b {
            // build b
        }
        if c {
            // build c
        }
        return
    }
    func setA() -> myClass {
        a = true
        return self
    }
    func setB() -> myClass {
        b = true
        return self
    }
    func setC() -> myClass {
        c = true
        return self
    }
}

This is my current solution. This way the caller does not need to care about the order. The build function will handle the order. And this is what I want. My question however is, can I do this without using bools? is there a more clean solution to achieve the same thing?

Aucun commentaire:

Enregistrer un commentaire