Parameter defaults and Optional function parameters in Swift

This post has been updated for Swift 3.0 here.

This post has been updated for Swift 3.0 here.

Swift has an interesting multi-pronged approach to dealing with default and optional function parameters, based in part on its relationship with Objective C and part inspired by other approaches.
It’s worth exploring the options. (To make the func parameters work more closely to how they’ll work in an Application, I’ve placed the functions in a class.)

Optional function parameters approach 1

First of all, let’s look at one approach to optional parameters:

func printFirstName(firstName:String) {
    println(firstName)
}
func printFirstName(firstName:String,surname:String) {
    println("\(firstName) \(surname)")
}
printFirstName("Joe") //prints Joe
printFirstName("Joe", "Blow") //prints Joe Blow

Wait – there are two functions with the same name? And why is the second function called printFirstName, when it clearly has a parameter called ‘surname’?
Well this is the same approach Objective C took, where the function wasn’t just defined by its name, but its parameters as well. So we have two functions – one is ‘printFirstName(firstName)’ and the other is printFirstName(firstName,surname)

Parameters with default values approach 1

This technique can also be a way to define default parameters, where the function with less parameters can call the function with extra parameters, defining defaults.

func printFirstName(firstName:String) {
    printFirstName(firstName,"Smith")
}
func printFirstName(firstName:String,surname:String) {
    println("\(firstName) \(surname)")
}

printFirstName("Joe")    //prints Joe Smith
printFirstName("Joe", "Blow")    //prints Joe Blow

This technique of optional parameters is consistent with the approach Objective C took and was necessary to include in Swift to be able to interpret underlying Objective C code. (I discussed optional parameters in Objective C in a previous blog post here).

Optional function parameters approach 2

As Swift has an Optional variable type, making a parameter Optional, would obviously make it optional 😉 However this doesn’t mean you don’t need to pass anything – you still need to pass nil, and deal with checking the optional contains something in the function.

func printFirstName(firstName:String,surname:String?) {
    if let unwrappedSurname = surname {
        println("\(firstName) \(unwrappedSurname)")
    } else {
        println(firstName)
    }

}
printFirstName("Joe",nil)    //prints Joe
printFirstName("Joe", "Blow")    //prints Joe Blow

Parameters with default values approach 2

Somewhere along the beta line, the Swift engineers made the brilliant decision to introduce true default values for parameters. Parameters with default values have a few special attributes:

  • they need to be declared at the end of the function definition
  • These parameters with defaults can be left out when calling the function
  • If you do want to include the parameter when calling the function, it’s external parameter name is obligatory
  • Which makes possible something really cool – parameters can be included in any order!
func printFirstName(surname:String="Blow",firstName:String="Joe",middleName:String="Andrew") {
    println("\(firstName) \(middleName) \(surname)")
}
printFirstName(firstName: "John", middleName: "Juan", surname: "Smith")    //prints John Juan Smith
printFirstName(firstName: "John")    //parameters left out! prints John Andrew Blow
printFirstName(firstName: "John", surname: "Smith", middleName: "Julius")    //parameters out of order! prints John Julius Smith

Optional function parameters approach 3

Which of course makes it possible for an ‘Optional’ variable to have a nil default value. So with a simple tweak to our previous default values example, we can introduce a true optional parameter, using the Optional type.

func printFirstName(firstName:String,surname:String?=nil) {
    if let unwrappedSurname = surname {
        println("\(firstName) \(unwrappedSurname)")
    } else {
        println(firstName)
    }

}
printFirstName("Joe")    //prints Joe
printFirstName("Joe", surname: "Blow")    //prints Joe Blow

Be careful with naming conflicts mixing these approaches – if you have multiple functions with the same name but different parameters, and one of them has optional parameters, and there’s a possibility that Swift won’t know which function you’re referring to, there’s a naming conflict and the compiler will complain.

Good luck with your Swift functions, hopefully this has been helpful. As I said at the beginning of this post, for info just on function parameters in Swift, click on my post here.

In other news, huge update now out for Subtitles Viewer!

Subtitles Viewercinema

Interactive developer, Author - iOS development with Swift - book coming 2017 https://manning.com/books/ios-development-with-swift

Tagged with: , ,
Posted in Swift
2 comments on “Parameter defaults and Optional function parameters in Swift
  1. […] For more on func parameters, I look into optional parameters here. […]

  2. […] For more on optional parameters, I’ve taken a look at them in Swift here. […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: