Closures, Extensions and Generics in Swift


Closures are self contained lines of code that can be passed around the application and similar to blocks in Objective-C. A typical closure syntax in Swift looks as shown below

Closure Syntax

{ (parameters) -> return type in 

Example closure in Swift

{ (name:String, message:String -> (String) in 
	message + " " + name + " !!!"


In the above code example, a closure has been assigned to a variable. The purpose of this closure is to concatenate the string parameters and return the appended message as return parameter.

Type Inference

The example closure can modified to ignore to the parameter types and closure supports type inference.

var greetings = { (name, message) -> (String) in 
	return message + " " + name + " !!!"


Implicit return

In single expression closure, you can omit the return keyword.

var numbers = [23,45,67,89,89,78]
	numbers.sort { (number1, number2) -> Bool in
	return number1 < number2

// numbers.sort { number1, number2 in return number1 < number2 }
numbers.sort { number1, number2 in number1 < number2 } // Shorthand argument syntax
numbers.sort { $0 < swift }

Shorthand Argument Syntax

Swift supports shorthand argument names for inline closures. In the above example used for implicit returns, the two parameters can be removed and represented in shorthand arguments as shown below.

numbers.sort { $0 < swift }

Trailing Closure

In a function with closure as the last parameter, the closure can be treated as trailing closures i.e closures outside the function parenthesis call. This is quite helpful in reducing the long closure expression. For example, the sorted function has closure as the last parameter and with trailing closure this becomes as shown below.

var numbers = [23,45,67,89,89,78]
var sortedNumbers = sorted(numbers, {$0 > swift}) // Without trailing closure
// var sortedNumbers = sorted(numbers) {$0 > swift} // represented as trailing closure



Swift extensions are similar to category in Objective-C which adds new functionally to existing class, enumeration or Struct. Extension does not require the source code of original class or enumeration type or struct to extend their functionality.

Listed below is an example which extends String class. A new function fromDouble has been added to String class which takes a double value and returns String.

 extension String {
static func fromDouble(doubleValue: Double) -> String {
	var temp = String(format: "%.2f", doubleValue)
	return temp as String


Generics are code that produces the same result irrespective of the data type. Listed below is a function that accepts an array of type string and reverses the array items.

let strTemp = ["Deepak","John","Steve","Ravi","Ganesh"]

// reverse array with String
func reverseString(items: Array) -> Array {
    var temp = Array()
    return items.reverse()

Now the below function accepts array of number and reverses the items

 let numbers = [23,45,56,78,98]
// reverse array with numbers
func reverseNumber(items: Array) -> Array {
    return items.reverse()

Generics solves the problem of having different set of code for different data types by implemting the functionality for a generic type.

let  strTemp  =   ["Deepak","John","Steve","Ravi","Ganesh"]
let  numbers  =   [23,45,56,78,98]

func reverseItems(items:[T])-> [T] {
    return items.reverse()

You can also implement a Generic class with this function as shown below.

let strTemp = ["Deepak","John","Steve","Ravi","Ganesh"]

class ReverseDemo {
	func reverseItems(items:[P])-> [P] {
    	return items.reverse()
let reverseDemo = ReverseDemo()

Swift Operations with Generics

Let us say you want to create a generic function that returns the square value of the given number. The immediate solution that comes to your mind is

func squareOfNumber(number:M  -> M{
    return number * number

This is not as straight forward as we think, you would notice an error – “Binary operator ‘*’ cannot be applied to two M operands”. The generic data type does not recogonize the operator ‘*’. We can fix this by creating a new protocol that tells about this operator ‘*’ and Generic type should conform to this protocol as shown below.

protocol Multipliable {
    func *(lhs:Self, rhs: Self) -> Self

func squareOfNumber(number:M  -> M{
    return number * number

Then add an extension to Int, Float and other required types and make them conform to Multipliable protocol.

extension Int: Multipliable {}
extension Float: Multipliable {}


Download source code from gitHub (Generic)

In Category: Apple, Develop, Programming

Ravi Shankar

A polyglot software developer and now exploring Swift and iOS development. If you would like to learn from me then check out services page.

Show 0 Comments
No comments yet. Be the first.

Leave a Comment