Swift Tutorial - Tutorialspoint

(backadmin) #1

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


true

The initial array to be sorted for icecream is given as "Swift" and "great". Function to sort
the array is declared as string datatype and its return type is mentioned as Boolean. Both
the strings are compared and sorted in ascending order and stored in a new array. If the
sorting is performed successful the function will return a true value else it will return false.


Closure expression syntax uses


 constant parameters,

 variable parameters, and

 inout parameters.

Closure expression did not support default values. Variadic parameters and Tuples can
also be used as parameter types and return types.


let sum = {(no1: Int, no2: Int) - > Int in
return no1 + no2
}
let digits = sum( 10 , 20 )
println(digits)

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


30


The parameters and return type declarations mentioned in the function statement can also
be represented by the inline closure expression function with 'in' keyword. Once declaring
parameter and return types 'in' keyword is used to denote that the body of the closure.


Single Expression Implicit Returns


Here, the function type of the sorted function's second argument makes it clear that a Bool
value must be returned by the closure. Because the closure's body contains a single
expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return
keyword can be omitted.


To return a Single expression statement in expression closures 'return' keyword is omitted
in its declaration part.


let count = [ 5 , 10 , - 6 , 75 , 20 ]
var descending = sorted(count, { n1, n2 in n1 > n2 })
var ascending = sorted(count, { n1, n2 in n1 < n2 })
Free download pdf