DEV Community

Neeraj Gupta for DSC CIET

Posted on

1

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.

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more