DEV Community

Neeraj Gupta for DSC CIET

Posted on

Closures in Swift ( Intro)

Brief Introduction About Swift

Swift is a language developed by Apple which is made using modern approach, include safety features and software design patterns. As the name suggests swift is fast, safe and easy to use. It is basically made a replacement for c-based family(C, C++ and Objective-C). It can be used to make apps and can be also used for cloud services and it is among the fastest growing languages.

Closures in Swift

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures are similar to block in C ( Block Statements are the one in which multiple statements of code are defined inside Curly Braces ( { } ) and are treated as single statement ). We can also say that closures are similar to functions.

General Syntax

{ (<#parameters#>) -> <#return type#> in
    <#statements#>
}
Enter fullscreen mode Exit fullscreen mode

Syntax Difference between Closure and Functions

Functions

Let's say we want to add two numbers then we will define a functions as:

func addTwoNumbers(numberOne: Int, numberTwo: Int) -> Int {
    return (numberOne + numberTwo)
}

addTwoNumbers(numberOne: 2, numberTwo: 3)
//Output : 5
Enter fullscreen mode Exit fullscreen mode

Closures

Now let's see how closure with same functionality can be defined:

let additionOfTwoNumbers: (Int, Int) -> Int = { (numberOne, numberTwo) in
    return (numberOne + numberTwo)
}

additionOfTwoNumbers(2,3)
//Output : 5
Enter fullscreen mode Exit fullscreen mode

When To Use Closures

Closures are although similar to functions but we generally use them when we want to carry out heavy and time consuming tasks like API Parsing as Closures carry out the process simantaneously alongside other code and returns data when completed.

That's it for this post see you all next time.

Top comments (0)