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
, for segue
, or segue
?
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".
Swift Function Declarationfunc - keyword used to declare a function.
You write an in-out parameter by placing the inout keyword right before a parameter's type. An in-out parameter has a value that's passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.
In Swift, variadic parameters are the special type of parameters available in the function. It is used to accept zero or more values of the same type in the function. It is also used when the input value of the parameter is varied at the time when the function is called.
A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With