Functions in Swift: Parameters and Return Types



Functions in Swift: Parameters and Return Types


I think we’ve gone over the basics of variables in Swift enough.  It is time to talk about functions in Swift.  Now, we have talked about these to some extent before, and I took it as a given that people would understand a bit.  But now I think it is time to actually start diving in and explaining more specifics.
Functions are blocks of code that perform a task.  You can then call these functions at different places, which makes fixing bugs much easier than the alternative.  If you just copied and pasted the code everywhere, and you found a bug, you would have to change each one to fix that bug.  With functions, you just change it one place, and everything that calls it gets the new fixed version of that block of code.  The entire app itself is wrapped within a function called “main”, but you don’t normally interact with it, unless there’s a crash.  Functions usually take arguments, and very often return data back to where it was called from.

Vocabulary Lesson

There are a few words that I’ll use here that it may be best to have defined outright, so here goes:
  • Function Signature (aka Signature):  The top line of the function, outside of that function’s curly braces.  This describes the inputs, return type, and visibility of a function.
  • Parameters:  The inputs to a function.  These are the variables created in the function signature, for use inside the function to do its job.
  • Arguments:  Where the parameters come from.  When you call a function, and give it the appropriate inputs, these are called arguments.
  • Arity:  The number of arguments a function takes.

Function parameters

For these examples, I am going to show functions with no return types, just to make the syntax simpler to just demonstrate differences in function parameters.  If you want to read about return types, skip ahead to the Return Types for Functions section.

No Parameters

Like I had mentioned, this could be used as something to generate something randomly or do some sort of side effect like toggle something or play a sound.  These are the simplest ones.  A no parameter function would look like this:
Very simple, it takes no parameters, and no arguments.  Inside of this one, you would probably pass some audio file to a media player or whatnot and just have it play.

One Parameter with No External Name

Next, we take on one parameter.  This will have a name for use internal to the function, and specify its type.  In Objective-C, all function parameters were marked with names (except for the first one) that you would have to type each time you called.  Swift allows you to continue to do that, and even recommends you to.  Just to show the basics, and then build on it, I am going to show without external names first.  If you want to see how to give them internal and external names, skip to the Naming Parameters section.
You can see from our talks on Swift Variables, that we define the type of that input the same way, with the name of the variable, followed by a colon, and then the type itself.

Multiple parameters with no external name:

This isn’t much harder, but I thought I would separate it just in case.  It is basically the same as the single argument, but just with commas between the different parameters:
This has changed since the introduction of Swift 2.  Now, methods and functions follow the same rules, so if you want multiple parameters with no external name, you must use the ” _ ” underscore character as its external name:

Variadic Parameters – Unspecified number of parameters

These are interesting.  You can actually create a method that works on any number of parameters, well, any number of the same type.  Basically, it will create an array of the values you put in, then you can iterate through them and do whatever you want.  You could have a method that sums all the numbers sent into it, or maybe one that puts a bunch of strings together joined by spaces.  Basically, you say a value, give it its type, and then add three period characters afterwards to make it a variadic parameter.  For example:
You would call it like this:
Whether that exact function is a good idea is inconsequential (and yes, I know there is an extra space at the end), it nonetheless takes as many parameters as you want.
You can have more than just the Variadic parameter in your function prototype
, but the variadic parameter must be the last one listed.  From Swift 2 onwards, a Variadic parameter can be in any position in the function signature.  Prior to it, it could only be put at the end, so now:
You also can only have one variadic parameter per function.  Apple’s iBook explicitly states that you can only use one variadic parameter per function.

Naming Parameters

It is common in Objective-C to name each of your parameters.  While I started showing you how to do it without having to type them when calling, it is often a good idea to have them as part of your call to this function.  It makes the code much more understandable (but longer), since you know what each parameter is without having to look up the function.  There are two ways to do this.

Use a different External Name

If you want a more descriptive name when calling it, but a shorter name to use internally, you just write the external name before the internal name, like so:

Use the Internal Name

If the internal name for the parameter is good enough, why not use it?
All you do here is put a hash symbol before the internal name, so we would get:
Swift 2 removed the ability to use the hash symbol to reuse the internal name as the external name (I guess I was among the few that new what it did), so now you just explicitly type an external name:

Return Types for Functions

Like function parameters, you can return different amounts.  We’ve already seen functions with no return type.  Additionally, a function can return one, multiple (known number though, no variadic return types, an array is the closest you get).  The multiple return value is called a “tuple”.  According to Dictionary.com, both pronunciations of it are valid (too-pull and tuh-pull).  Some people suggest that it should be “tuh-pull”, since it is related to words like “quintuple” or “octuple.”  I personally like saying “too-pull” myself, but that’s just me.
Update November 5, 2014:  You can read more about tuples in the post Tuples in Swift: Create, Read, and Return.

Single Return Type

Most programming languages only have one return type, if any.  As such, of course it is possible to do so in Swift.  I have not personally seen it written like it is in Swift elsewhere, but simple nonetheless:
You just make that arrow character, which is just a hyphen and a greater-than symbol, and then follow it with the type name.

Multiple Return Types

It sounds like it should be complex, but they really set it up similar to how you set parameters, just on the return type side, so you basically enclose your return types in parenthesis and give each a name and type separated by a comma after that arrow ( -> ), such as:
As you can see, you just return it between parenthesis.  You would then use it like this:

Optional Multiple Return Types

You would just return nil, instead of something in parenthesis like you normally would when returning a tuple.




Post a Comment

Previous Post Next Post