What are the new “for”, “at”, “in” keywords in Swift3 function declarations?

The syntax allow you to label arguments twice – once for use within the function (the parameter name) and once for use when calling (the argument label). By default these two will be the same (like with sender in your example), but they differ when it makes a function more readable at the call site:

prepare(for: aSegue, sender: something)

being more readable-as-a-sentence than:

prepare(segue: aSegue, sender: something)

Which sounds like you’re preparing the segue, not preparing for the segue.

for would be a dreadful name to use internally in the function to refer to the segue, so you can use a different one if you require.

The idea is to meet the sometimes conflicting goals of readability at the call site and sensible naming in the implementation.

When defining a function, if you are going to use separate argument labels and parameter names, you specify the argument label first, and the parameter name second:

func sayHello(to name: String) {
    print("Hello " + name)
}

sayHello(to: "Pekka")

to only has relevance when calling the function. name is used inside the function.

Leave a Comment