Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Builder pattern set method in swift

Tags:

ios

swift

builder

I am just shifted from Android base to ios, looking for builder pattern get and set method in swift unable to find anything like it. Found following only

var ptype : String? {
    get{
        return self.ptype
    }set (ptype) {
        self.ptype = ptype
    }
}
like image 422
amodkanthe Avatar asked Apr 14 '26 05:04

amodkanthe


1 Answers

After using so many libraries written in Swift, I have rarely seen people use the builder pattern in Swift.

I think the Builder Pattern's main advantages can already be achieved with Swift's other language features. You can totally create a constructor where all the parameters are optional, and you almost just recreated the builder pattern in Swift:

class Foo {
    let a: Int
    let b: String
    let c: Bool

    init(a: Int = 0, b: String = "", c: Bool = false) {
        self.a = a
        self.b = b
        self.c = c
    }
}

You can create a Foo like this:

// You can omit any of the arguments, just like the builder pattern
Foo(
    a: 123
    b: "Hello World"
    c: true
)

I would argue that's an even cleaner version of something like this in Java:

new FooBuilder()
    .setA(123)
    .setB("Hello World")
    .setC(true)
    .build()

But if you insist, here is some really verbose Swift that implements the Builder pattern:

class Foo {
    private(set) var a: Int = 0
    private(set) var b: String = ""
    private(set) var c: Bool = false

    init(a: Int = 0, b: String = "", c: Bool = false) {
        self.a = a
        self.b = b
        self.c = c
    }

    class Builder {
        private var innerFoo = Foo()

        @discardableResult
        func withA(_ a: Int) -> Builder {
            innerFoo.a = a
            return self
        }

        @discardableResult
        func withB(_ b: String) -> Builder {
            innerFoo.b = b
            return self
        }

        @discardableResult
        func withC(_ c: Bool) -> Builder {
            innerFoo.c = c
            return self
        }

        func build() -> Foo {
            return innerFoo
        }
    }
}
like image 126
Sweeper Avatar answered Apr 15 '26 19:04

Sweeper