iOS Scholar's Blog

iOS Scholar's Blog

iOS Development Tutorials, Tips & Tricks and more

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Functions in Swift with Multiple Return Types and External Parameters

Swift Functions with Multiple Return Types and External Parameters
Annotate Parameters, Returned Values and more...

Note: Updated for Xcode6 Beta 3
Functions in Swift are flexible are powerful, as they behave like a bridge between the C style functions with or without parameters, along with a return type and complex Objective C functions which maintain high level of readability with parameter names embedded* in the functions names.

(*Swift’s Functions meet the latter requirement with External Parameters - more on external parameters later in this article)

Here is short tutorial giving an quick introduction to the functions in Swift.

Let's take a look at the syntax with a simple example:

func countMultiples(multipleOf:Int, numbers: [Int]) -> Int
{
    var count = 0
    for aNumber in numbers {
            if aNumber % multipleOf == 0
            {
                count++
        }
    }
    return count
}

var numbers = [3,6,12,55,42]
println(countMultiples(3,numbers)) // prints 4
println(countMultiples(2,numbers)) // prints 3

The func keyword marks the beginning of the function. It’s followed by the function name countMultiples. The parenthesis enclose two parameters, notice that the return type is specified after the parameter name with a colon. Finally we put the return type of the function after an arrow ->

The simple function above counts the multiples of the first parameter in the array of integers, which is the second parameter.

We could write a function with no parameters by omitting the parameters and leaving the parenthesis empty, and a function with no (or void) return type by omitting the  arrow and Int keyword.

But that’s not all. We can make a function return multiple values too. Let's consider the following example.

Multiple Return Values

func largestAndSmallest(inArray: [Int]) -> (IntInt)
{
    var largest = inArray[0]
    var smallest = inArray[0]
    for index in 1..<inArray.count {
        if largest < inArray[index]{
            largest = inArray[index]
        }
        if smallest > inArray[index]{
            smallest = inArray[index]
        }

    }
    return(largest, smallest)
}

The function takes an array as its argument and returns two values - the largest and smallest in the array. We can either print the returned values:
println(largestAndSmallest([2,3,43,1]))
//Prints: (43,1)

Or we could accept these values in different variables and further process them:
var (m,n) = largestAndSmallest([32,45,77,3])
println("Sum of Largest and Smallest in [32,45,77,3] is \(m+n)")
//Prints: Sum of Largest and Smallest in [32,45,77,3] is 80

(By the way, there is a problem in above function, did you figure it out already?)

External Parameters

If we consider the function in the first example again:

func countMultiples(multipleOf:Int, numbers: [Int]) -> Int

In Objective C, we would have called a similar function like this:
[self countMultiplesOfNumber:3 inArray:array OfSize:5]

Notice the use of parameter names to make the function call more readable and intuitive.

To achieve the same level of clarity while calling Swift functions, we can use external names.

Now, let's check out the same function with external parameters.
func countMultiples(ofNumber number:Int, inNumbers numbers: [Int]) -> Int
{
    var count = 0
    for aNumber in numbers {
            if aNumber % number == 0
            {
                count++
        }
    }
    return count
}

While calling this function, we would now have to compulsorily use the external parameters. The improved readability in the function calls makes the effort worthwhile:


var numbers = [3,6,12,55,42]
println(countMultiples(ofNumber:3, inNumbers:numbers)) // prints 4
println(countMultiples(ofNumber:2, inNumbers:[41,2,3,5,6])) // prints 2

But thinking of two names for each parameter might be tough sometimes, and sometimes not really useful, in which case w should simply precede the parameter names in the function definition with # symbol. A parameter name preceded with hash symbols, e.g. #ofNumber can be used both as external parameter (label in the function call) and internal parameter, i.e. Inside the function.

We’ll cover the above with example, along with shorthand External Parameters, Default Parameters, Variable and Inout Parameters in next tutorial - Swift Functions - Shorthand External, Default, Inout and Variable Parameters. And also sending functions as parameters, and returning functions (function types) in an upcoming tutorial

Important: External parameter names play a role in resolving ambiguity in overloaded functions. We can have a function with same parameter and return type declared again if the external parameter name is different.
(That’s because, once you specify the external parameter names, you will have to use them in function call, thus resolving the ambiguity raised due to same type of parameters.)
PS: The image below shows a function which prints the names of the most exciting features (one basic and one advanced) of Swift IMHO. What will your version of this function be? Please do let me know in comments.

Swift Functions - Multiple Return Types and External Parameters

What will your version be? (:

 © 2014, UV Associates.
All rights Reserved.