Functions are small modules or chunk of code. Swift’s function syntax is so flexible that it allows to write a function inside a function.
Here is a syntax:
func firstFunction(arguments) -> returnType{
func secondFunction(arguments) -> returnType{
func thirdFunction(arguments) -> returnType{
and so on.
}
}
}
Here is an example(code) from above syntax:
func addRandomNumAndCheckIfOdd(inout passedNumber: Int) -> Bool {
passedNumber += Int(arc4random_uniform(UInt32(10))); // adding random number between 0-9 to passed number
// function will check if the obtained number is Odd or not
func isOdd(numToCheck:Int)->Bool{
if numToCheck%2 == 0 {
return false
}
return true
}
return isOdd(passedNumber)
}
In the above example we have created a function “addRandomNumAndCheckIfOdd” which will add a random number and check if it’s odd or not.
We have passed an argument ‘passedNumber’ with reference so that it can be modified. A random number ranging from 0-9 will be added to passed number.
while returning we are checking if the modified number is odd or not using function inside a function flexibility provided by swift.
Function inside a function will not be executed until and unless it is called, compiler will skip the function otherwise.
0 Comment(s)