Swift Tutorial - Tutorialspoint

(backadmin) #1
println(descending)
println(ascending)

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


[75, 20, 10, 5, -6]


[-6, 5, 10, 20, 75]


The statement itself clearly defines that when string1 is greater than string 2 return true
otherwise false hence return statement is omitted here.


Known Type Closures


Consider the addition of two numbers. We know that addition will return the integer
datatype. Hence known type closures are declared as


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

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


- 10


Declaring Shorthand Argument Names as Closures


Swift automatically provides shorthand argument names to inline closures, which can be
used to refer to the values of the closure's arguments by the names $0, $1, $2, and so
on.


var shorthand: (String, String) - > String
shorthand = { $1 }
println(shorthand("100", "200"))

Here, $0 and $1 refer to the closure's first and second String arguments.


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


200


Swift facilitates the user to represent Inline closures as shorthand argument names by
representing $0, $1, $2 --- $n.


Closures argument list is omitted in definition section when we represent shorthand
argument names inside closure expressions. Based on the function type the shorthand

Free download pdf