Constructors in Swift

Jun 18, 2022 1 min read
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")
Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.