Constructors in Swift

Time after time we want to scale our app or provide more options to our functions that are not necessarily required when calling them. In other languages we have constructors and at times the code has to be repeated, but not in Swift!

Functions

Let's imagine you have 2 functions, both with different arguments:

func multi(acceptsA: String) { }

func multi(acceptsA: String, acceptsB: String) { }

How can you combine them into 1? Simple because fortunately Swift supports parameters with default values, this is how it would look:

func multi(acceptsA: String, acceptsB: String? = nil) { }

Now you can call them like so:

multi(acceptsA: "something")
// or
multi(acceptsA: "something", acceptsB: "somethingElse")