Swift method parameters, coffee, sugar & milk

Swift methods are quite different comparing to Objective-C methods. It comes with many possibilities for method parameters, which makes it sometimes a bit hard to understand whats happening. In some cases methods aren’t even readable enough in my opinion.

Swift comes with the possibility to add # and _ inside method declaration. The hash enforces to use the parameter when calling the method, the underscore instead enforces to not use the parameter. Furthermore it’s possible to change the parameter name to use when calling the method. This results in the following possibilities:

func createCoffee(sugar:Bool)


func createCoffee(# sugar:Bool)

createCoffee(sugar: true)

func createCoffee(usingSugar sugar:Bool)

createCoffee(usingSugar: true)

func createCoffee(# sugar:Bool, milk:Bool)

createCoffee(sugar: true, milk: true) 

func createCoffee(sugar:Bool, _ milk:Bool)

createCoffee(true, true)

func createCoffee(# sugar:Bool, andMilk milk:Bool)
createCoffee(sugar: true, andMilk: true)

func createCoffee(usingSugar sugar:Bool, andMilk milk:Bool)
createCoffee(usingSugar: true, andMilk: true)

Important part here is that the compiler wont allow you to use ‘with’ in the external parameter declaration. Something like this isn’t possible:

func createCoffee(withSugar sugar:Bool, andMilk milk:Bool)
createCoffee(withSugar: true, andMilk: true)

As it enforces you to use the hash sign.

Hash sign benefits

The hash sign also makes it possible to use the same method declaration. For example:

func createCoffee(# milk:Bool)

func createCoffee(# sugar:Bool)

Without the hash sign this would result in the error “Invalid redeclaration of ‘createCoffee'”

Bringing it all together

With optional parameters it’s even possible to create above methods in once. For example:

func createCoffee(usingSugar sugar:Bool? = false, usingMilk milk:Bool? = false)

createCoffee(usingSugar: true)
createCoffee(usingSugar: true, usingMilk:true)

Have fun declaring your new Swift methods!