

{"id":120674,"date":"2023-11-23T18:00:56","date_gmt":"2023-11-23T12:30:56","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=120674"},"modified":"2023-11-23T18:05:18","modified_gmt":"2023-11-23T12:35:18","slug":"closures-in-swift","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/","title":{"rendered":"Closures in Swift"},"content":{"rendered":"<p>Closures are blocks of code that execute together but without a named function. These are similar to lambdas in other programming languages. We define it without using the func keyword. It can accept parameters and return values just like functions.<\/p>\n<p>In this article, we\u2019ll learn about the basics of closures and how we can use them as function parameters or operator functions. We\u2019ll also go through other related concepts along with relevant examples.<\/p>\n<h2>Declaration and Calling Closure in Swift<\/h2>\n<p>We define a closure without the func keyword and a function name. We can assign closures to variables or constants. We optionally use the in keyword to separate the return type from the body of the closure.<\/p>\n<p><strong>Syntax for closures.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">{ (parameters) -&gt; returnType in\r\n    \/\/code\r\n}<\/pre>\n<p>We call a closure by writing the name of the variable it is assigned to, followed by parentheses ().<\/p>\n<p>Unlike functions, we don&#8217;t need to write the parameter name.<\/p>\n<p><strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/Declaring a closure\r\nvar greetClosure = { (name: String) in\r\n    print(\"Hello from \\(name)!\")\r\n}\r\n\r\n\/\/Calling the closure\r\ngreetClosure(\"DataFlair\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello from DataFlair!<\/p>\n<h3>Closure Parameters<\/h3>\n<p>Closures can also accept parameters. Unlike in functions, while calling the closures, we don\u2019t need to write the argument label. <strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var sum = { (num1: Int, num2: Int)  in\r\n    print(\"Sum: \\(num1 + num2)\")\r\n}\r\n\r\nsum(20, 23)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Sum:<\/strong> 43<\/p>\n<p>We can also define closures without parameters.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let noParameterClosure = { () in\r\n    print(\"Hello from DataFlair!\")\r\n}\r\n\r\nnoParameterClosure()<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello from DataFlair!<\/p>\n<h3>Closure Return Value<\/h3>\n<p>Closures can have a return value just like a function. We need to specify the return type before returning a value. <strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var productClosure = { (num1: Int, num2: Int) -&gt; Int in\r\n    return num1*num2\r\n}\r\n\r\nvar answer = productClosure(21, 34)\r\nprint(\"The product is: \\(answer)\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>The product is:<\/strong> 714<\/p>\n<h3>Closure as Function Parameter<\/h3>\n<p>We can pass a closure as a parameter in a function. For example, we can create closures for mathematical operations, and those closures can be passed as a parameter in a function.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">func mathOperation(num1: Int, num2: Int, operation: (Int, Int) -&gt; Int) -&gt; Int {\r\n    return operation(num1, num2)\r\n}\r\n\r\nlet add = { (x: Int, y: Int) -&gt; Int in\r\n    return x + y\r\n}\r\n\r\nlet subtract = { (x: Int, y: Int) -&gt; Int in\r\n    return x - y\r\n}\r\n\r\nlet multiply = { (x: Int, y: Int) -&gt; Int in\r\n    return x * y\r\n}\r\nlet addResult = mathOperation(num1: 23,num2: 20, operation: add)\r\nlet subtractResult = mathOperation(num1: 23,num2: 20, operation: subtract)\r\nlet multiplyResult = mathOperation(num1: 23,num2: 20, operation: multiply)\r\nprint(\"Add Result: \\(addResult)\")\r\nprint(\"Subtract Result: \\(subtractResult)\")\r\nprint(\"Multiply Result: \\(multiplyResult)\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Add Result:<\/strong> 43<br \/>\n<strong>Subtract Result:<\/strong> 3<br \/>\n<strong>Multiply Result:<\/strong> 460<\/p>\n<h3>Shorthand Argument Names<\/h3>\n<p>Shorthand Arguments name refers to the parameters in the function concisely. It gives placeholders like $0 to the first parameter, $1 to the second and so on. Swift infers these automatically. It makes our code shorter. We can use these when we are writing closures for operations like filtering, sorting or mapping.<\/p>\n<p><strong>For example, we write a closure with shorthand argument names to create an even numbers array from an existing array.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let numbers = [41, 42, 43, 45, 47, 48, 49]\r\nlet evenNumbers = numbers.filter { $0 % 2 == 0 }\r\nprint(evenNumbers)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>[42, 48]<\/p>\n<h3>Operator Methods<\/h3>\n<p>We can use closures to create operator methods to enable custom behaviour for existing operators. These operators can be arithmetic, comparison operators or assignment operators. <strong>For example, we create a closure to sort the elements in ascending order.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let numbers = [12,7,34,5,62,3,21]\r\nlet sortedNumbers = numbers.sorted(by: &lt;)\r\nprint(sortedNumbers)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>[3, 5, 7, 12, 21, 34, 62]<\/p>\n<h3>Trailing Closure<\/h3>\n<p>In a trailing closure, we write the closure expression after the function call\u2019s parentheses. We can use this only when the closure is the last argument in the function. For example, Arrays in Swift use trailing closures in its method. One such method is the map(_:) method. This method accepts closure expressions as the only parameter.<\/p>\n<p><strong>Another example of trailing closure is as follows.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">func addOperation(num1: Int, num2: Int, operation: (Int) -&gt; Void) {\r\n   let sum = num1 + num2 \r\n   operation(sum)\r\n}\r\n\r\naddOperation(num1: 23, num2: 37) { answer in\r\n\r\n    print(\"Sum is \\(answer).\")\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>The sum is 60.<\/p>\n<h3>Autoclosure<\/h3>\n<p>Autoclosure automatically wraps the closure expression and postpones its evaluation until it is accessed. We can pass these without using braces when we call the function. We need to follow the syntax of including the @autoclosure keyword in the function definition. @autoclosure is an attribute that is applied to the parameters of a function.<\/p>\n<p>Note that we can encounter errors when we pass arguments to autoclosure.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/function that takes autoclosure\r\nfunc printGreeting(greeting: @autoclosure () -&gt; String){\r\n    print(greeting())\r\n}\r\n\/\/Calling function with autoclosure\r\nprintGreeting(greeting: \"Hello from DataFlair!\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello from DataFlair!<\/p>\n<h3>Capturing Values<\/h3>\n<p>We can capture and store values with the help of closures. We can refer to and modify these values inside the closure even if the variable or constant holding the values does not exist.<\/p>\n<p>For example, we have a function makeCounter(). It returns the closure increment() that captures the value of the count variable. When we call makeCounter(), the value of the count is increased by 1.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">func makeCounter() -&gt; () -&gt; Int {\r\n    var count = 0\r\n    \r\n    let increment: () -&gt; Int = {\r\n        count += 1\r\n        return count\r\n    }\r\n    \r\n    return increment\r\n}\r\n\r\nlet counter = makeCounter()\r\n\r\nfor i in 0..&lt;5{\r\n    print(\"Count \\(i): \\(counter())\")\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Count 0:<\/strong> 1<br \/>\n<strong>Count 1:<\/strong> 2<br \/>\n<strong>Count 2:<\/strong> 3<br \/>\n<strong>Count 3:<\/strong> 4<br \/>\n<strong>Count 4:<\/strong> 5<\/p>\n<h4>Capturing Reference Types<\/h4>\n<p>When we are dealing with reference types, closures capture the references to the instances.<\/p>\n<p><strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Example{\r\n    var arrayExample = [\"DataFlair\", \"Swift\"]\r\n}\r\n\r\nvar example1 = Example()\r\n\r\nlet referenceClosureCapture = {\r\n    print(\"Closure Capture for references: \\(example1.arrayExample)\")\r\n}\r\n\r\nreferenceClosureCapture()\r\nexample1.arrayExample.append(\"Closure\")\r\nreferenceClosureCapture()<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Closure Capture for references:<\/strong> [&#8220;DataFlair&#8221;, &#8220;Swift&#8221;]<br \/>\n<strong>Closure Capture for references:<\/strong> [&#8220;DataFlair&#8221;, &#8220;Swift&#8221;, &#8220;Closure&#8221;]<\/p>\n<h3>More about Closures<\/h3>\n<ul>\n<li>Global and nested functions are special kinds of closures.<\/li>\n<li>Closures have a name but don\u2019t capture any values that are Global Functions.<\/li>\n<li>Closures have a name, and capture values from the function enclosed are Nested Functions.<\/li>\n<li>Swift closure expressions are optimizations that promote clear and concise syntax in common cases. Some of these optimizations are type inference of parameter and return value, shorthand argument names, and trailing closure. These are explained in detail above.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>Swift provides a way to write functions without naming them. It can accept parameters and return variables. We can also assign them to variables and constants. In this article, we\u2019ve discussed the basics of closures. We have also gone through different kinds of closures, like trailing closures and auto closures. We have seen how we can capture values and reference values with the help of closures.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Closures are blocks of code that execute together but without a named function. These are similar to lambdas in other programming languages. We define it without using the func keyword. It can accept parameters&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":120676,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27789],"tags":[28458,21771,28457,28282],"class_list":["post-120674","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift-tutorials","tag-closures-swift","tag-swift","tag-swift-closures","tag-swift-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Closures in Swift - DataFlair<\/title>\n<meta name=\"description\" content=\"In this article, we\u2019ll learn about the basics of swift closures and how we can use them as function parameters or operator functions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/closures-in-swift\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Closures in Swift - DataFlair\" \/>\n<meta property=\"og:description\" content=\"In this article, we\u2019ll learn about the basics of swift closures and how we can use them as function parameters or operator functions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/closures-in-swift\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-23T12:30:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-23T12:35:18+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-closures.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Closures in Swift - DataFlair","description":"In this article, we\u2019ll learn about the basics of swift closures and how we can use them as function parameters or operator functions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/","og_locale":"en_US","og_type":"article","og_title":"Closures in Swift - DataFlair","og_description":"In this article, we\u2019ll learn about the basics of swift closures and how we can use them as function parameters or operator functions.","og_url":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-11-23T12:30:56+00:00","article_modified_time":"2023-11-23T12:35:18+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-closures.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Closures in Swift","datePublished":"2023-11-23T12:30:56+00:00","dateModified":"2023-11-23T12:35:18+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/"},"wordCount":780,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-closures.webp","keywords":["closures swift","Swift","swift closures","swift tutorial"],"articleSection":["Swift Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/closures-in-swift\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/","url":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/","name":"Closures in Swift - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-closures.webp","datePublished":"2023-11-23T12:30:56+00:00","dateModified":"2023-11-23T12:35:18+00:00","description":"In this article, we\u2019ll learn about the basics of swift closures and how we can use them as function parameters or operator functions.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/closures-in-swift\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-closures.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-closures.webp","width":1200,"height":628,"caption":"swift closures"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/closures-in-swift\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Swift Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/swift-tutorials\/"},{"@type":"ListItem","position":3,"name":"Closures in Swift"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120674","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=120674"}],"version-history":[{"count":4,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120674\/revisions"}],"predecessor-version":[{"id":126802,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120674\/revisions\/126802"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/120676"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=120674"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=120674"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=120674"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}