Pekka 웃 Pekka 웃 - 1 year ago 68
Swift Question

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

I'm working through a beginners' tutorial on Swift that is written in Swift 2.

It contains code like (random example)

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {

This has changed in Swift 3 (I'm using XCode 8 Beta), and the IDE helpfully converts this to the new (beautiful!) notation:

override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {

What confuses me here is the "for" in "for segue:". I get why it's there, but what kind of an element is it syntactically? Is the parameter named
for segue
, or

Is it mere decoration - an element with no meaning but to help the developer understand the context? Does it do anything else? Does the concept have a name? Can I use it in my own methods?

I see the same happening with "in" and "at".

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download