Swift Tutorial - Tutorialspoint

(backadmin) #1
Statement 2
---
Statement n
}

Following is a simple example:


let divide = {(val1: Int, val2: Int) - > Int in
return val1 / val2
}
let result = divide( 200 , 20 )
println (result)

When we run the above program using playground, we get the following result:


10


Expressions in Closures


Nested functions provide a convenient way of naming and defining blocks of code. Instead
of representing the whole function declaration and name constructs are used to denote
shorter functions. Representing the function in a clear brief statement with focused syntax
is achieved through closure expressions.


Ascending Order Program


Sorting a string is achieved by the Swifts key reserved function "sorted" which is already
available in the standard library. The function will sort the given strings in the ascending
order and returns the elements in a new array with same size and data type mentioned in
the old array. The old array remains the same.


Two arguments are represented inside the sorted function


 Values of Known type represented as arrays.

 Array contents (Int, Int) and returns a Boolean value (Bool) if the array is sorted
properly it will return true value otherwise it will return false.

A normal function with input string is written and passed to the sorted function to get the
strings sorted to new array which is shown below


func ascend(s1: String, s2: String) - > Bool {
return s1 > s2
}
let stringcmp = ascend("swift", "great")
println (stringcmp)
Free download pdf