Documente Academic
Documente Profesional
Documente Cultură
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
func test()
{
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
In Swift, functions can return multiple values using tuple. Below function takes string and returns
a tuple.
var nums = 0;
var letters=0;
var others = 0;
return (nums,letters,others)
}
We can give meaningful names for the arguments for better code walk-through.
return "";
}
toLower(string:"Ravi");
join(string:"Ravi",with:"Kusuma");
Like other programming languages, Swift supports default parameters for functions.
return str1+with+str2;
}
Swift automatically provider external parameter name for the default parameter.
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).
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.
var x: Int = 1
var y: Int = 2
swapNumbers(&x,&y)
callFun(addNumber, 1,2);
9). Returns functions as return types
Swift supports function with in the function. Nested function scope is hidden outside the main
function.
print()
return a+b;
}
Reference:Apple Documentaion