Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)

Functions


In Swift, it's very easy to create the functions using the func keyword, followed by the function name and parameters between the parentheses. Parentheses are required even if the function doesn't take parameters. So we will use parentheses without writing anything in between. For some other languages we need to use the void keyword for the function that doesn't take parameters. Parameters are comma separated and each one is combined with two items: the name and the type of parameters, separated by : (colon). Check this example of a simple function:

func sayHi(name:String)
{
    println("Hi \(name)")
}

sayHi("John") //Hi John

One of the great features that I love in Objective-C is that you can write a full description for each parameter in methods, which helps everyone, working in the project, to understand the code. The same is here in Swift; you can label parameters more easily. To do so, just type the name (description) before the parameter, or add # before the name of parameter, if the name is sufficient as a description and meaningful. Check these two examples:

func joinStrings(string1 str1:String, toString str2:String, joinWith j:String)
{
    println(str1 + j + str2)
}

joinStrings(string1: "John", toString: "Smith", joinWith: ",") //"John,Smith"

func joinStrings2(#string1:String, #toString:String, #glue:String)
{
    println(string1 + glue + toString)
}

joinStrings2(string1: "John", toString: "Deo",glue: "/") //"John/Deo"

As we saw in the first method, we wrote the description for each parameter, so that the code would be readable and understandable. In the second one, the parameter names were self-explained, and they needed no explanation. In such a case, we just added # before them, and then the compiler treated them as labels for parameters.

Like any function in any language, Swift may return results after the execution. Functions can return multiple values and not just a value like Objective-C, thanks to tuples! To do this, just write -> after the parentheses, and then add a tuple that describes the results:

func getMaxAndSum(arr:[Int]) -> (max:Int, sum:Int)
{
    var max = Int.min
    var sum = 0
    for num in arr{
        if num > max
        {
            max = num
        }
        sum += num
    }
    return(max, sum)
}

let result = getMaxAndSum([10, 20, 5])
result.max //20
result.sum //35