Vous êtes sur la page 1sur 5

Swift Functions in iOS for beginners

by Ravishanker Kusuma in Coding Jun 6th 2014 5 Comments

In this article, I have covered iOS Swift functions syntax, usage, features with examples. Topics
covered in this article are:
1) Swift function syntax
2) Swift function with multiple return values
3) functions with external parameter names
4) functions with Default parameters
5) Passing variable list as parameter
6) Constant and Variable parameters.
7) In-Out parameters(Pass By Reference).
8) Pass functions as parameter types
9) Returns functions as return types
10) Nested Swift functions

1.Swift function syntax

swift functions syntax looks like

func functionName(arg1:Type,arg2:Type,..) -> ReturnType


{

Below are the different examples of swift functions.

1.1). Simple function without argument without return value.

func test()
{

1.2) Function with Arguments, without return value

func test1(str:String)
{

}
func print(numb:Int, str:String)
{

}
//calling
test1("Ravi")
print(1,"Ravi")
1.3). Function with arguments and with return value

Return values is represented using ->

func sum(a:Int,b:Int) -> Int


{
return a+b;
}

var out = sum(1,2)

2). Function with multiple return values

In Swift, functions can return multiple values using tuple. Below function takes string and returns
a tuple.

func count(str:String) -> (numbers:Int,letters:Int,others:Int)


{

var nums = 0;
var letters=0;
var others = 0;

return (nums,letters,others)
}

//how to use tuple


var (numbers,letters,others) = count("abcd124edf@#")
println("number:\(numbers) letters:\(letters) others:\(others)")
//how to use tuple
var ret = count("abcd124edf@#")
println("number:\(ret.numbers) letters:\(ret.letters) others:\(ret.others)")

3) Functions with external parameter names

Objective-C supports external parameter names. For example,

[obj setValue:val forKey:key];

We can give meaningful names for the arguments for better code walk-through.

Swift also support Objective-C like external parameter names

func toLower(#string: String) ->String


{

return "";
}

toLower(string:"Ravi");

func join(#string: String, #with: String) ->String


{
return string+with;
}

join(string:"Ravi",with:"Kusuma");

4). Passing default parameters to functions

Like other programming languages, Swift supports default parameters for functions.

func join(str1:String,str2:String, with:String="") ->String


{

return str1+with+str2;
}

Swift automatically provider external parameter name for the default parameter.

//You need to specify parameter name, if the default parameter value is


given
var out1 = join("Hello","World",with:",") //Hello,World
var out2 = join("Hello","World") //Hello World

5). Passing variable list in the arguments

variable list type identified with


For example, a parameter with a name of numbers and a type of Int is made available within
the functions body as a constant array called numbers of type Int[].

func printNumbers(numbers: Int...)


{
for number in numbers
{
println(number);
}
}
//calling function
printNumbers(1,2)
printNumbers(1,2,3,4,5,6)

6) Constant and Variable parameters.

By Default, all the parameters are constants. Trying to the change the value of parameter results
in a compile-time error.

func testFun(str1:String)
{
str1 = "Ravi" //this gives compilation error.
}

if a an argument is specified as var, it as available as local variable, initialized with its value.
And it can be manipulated with in the body.
func testFun(var str1:String)
{
str1 = "Ravi" //updated str1 value is not visible outside the body.
}

Note: Changes made in the body are not visible outside the body. i.e.(Pass by value).

7) In-Out parameters (Pass by reference)

If you want to modify a variable inside the body and you want the changes persist out side the
body, define the parameter
as in-out parameter.

func swapNumbers(inout x: Int, inout y: Int)


{
let temp = x;
x=y;
y=temp;
}

var x: Int = 1
var y: Int = 2
swapNumbers(&x,&y)

println("x : \(x) y: \(y)") // x,y values are swapped

8). Pass functions as parameter types

func addNumber(a:Int,b:Int) ->Int


{
return a+b;
}

Above function type is identified with (Int,Int) -> Int

You can declare a variable with function type.

var mathFunction: (Int,Int) ->Int


mathFunction = addNumber;

var sum = mathFunction(1,2) //addNumber function is called.

You can pass the function as an argument to function like below.

func callFun(fun1: (Int,Int) -> Int,a:Int,b:Int)


{
println("Sum :\(fun1(a,b))"); //calls function and print the return value
}

callFun(addNumber, 1,2);
9). Returns functions as return types

You can return functions as return types. For example

func addNumber(a:Int,b:Int) -> Int


{
return a+b;
}

the above function can be returned like below

//(Int,Int) -> Int is the function type


func add() -> (Int,Int) -> Int
{
return addNumber;
}

var out = add()(1,2)

//add() returns addNumber function. so add()(1,2) returns the value.

10) Nested Swift functions

Swift supports function with in the function. Nested function scope is hidden outside the main
function.

func addNumber(a:Int,b:Int) -> Int


{
func print()
{
println("a:\(a) b:\(b)")
}

print()
return a+b;
}

Reference:Apple Documentaion

Vous aimerez peut-être aussi