![]() |
In Swift, Closures are known as self-contained blocks of functionality that can be passed around and used inside your code. They are quite similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can also capture and store references to any constants and variables from the context in which they are defined. ClosuresClosures in Swift are first-class citizens, which means they can be treated like any other type (such as strings, integers, and classes). They are often used for functional programming patterns, such as mapping and filtering arrays, and for asynchronous programming. They can also be passed as arguments to functions and can be returned from functions as well. Closures are a powerful and flexible feature of Swift, and they are used extensively in the language’s standard library and APIs. Syntax:
Example: Swift
Output: Hello, world! In this example, greet is a closure that simply prints a greeting to the console. You can call the closure by using its name followed by parentheses, just like a function. Here is an example of how to use closures in Swift, with explanations of each step and some screenshots of the output: Define a ClosureTo define a closure in Swift, you use the {} syntax and include the closure’s parameters, return type (if any), and body. Here is an example of a closure that takes two integers and returns their product:
Call the ClosureTo call a closure, you simply use its name followed by parentheses and any necessary arguments. For example:
Use the Closure in a FunctionYou can also pass closure as an argument to a function. Here is an example of a function that takes a closure as an argument and uses it to perform a calculation:
Example: Swift
Output: 35 Inferring Type From ContextIn Swift, you can often omit the type of a variable or constant when it can be inferred from the context. Swift may infer the types of a method’s parameters and the type of value it returns because the sorting closure is supplied as an argument to the method. A function of the form (String, String) -> Bool must be used as the argument because the sorted(by:) method is being called on an array of strings. This implies that the definition of the closure expression does not require the writing of the (String, String) and Bool types. When providing closure to a function or method as an inline closure expression, it is always feasible to deduce the parameter types and return types. As a result, whenever an inline closure is used as a function or method argument, you never need to write it in its entirety. Example: Swift
Output: hello world In the example above, the type of the sentence constant is inferred to be a String because it is the result of calling the concatenate(_:) function, which returns a string. The type of the word constant is inferred to be [String] because it is initialized with an array literal that contains only strings. Shorthand Argument NamesShorthand argument names refer to the arguments of a function or closure. Shorthand argument names are automatically provided to you by Swift and are a convenient way to refer to the arguments of a function or closure in a concise way. You can omit the closure’s argument list from its definition if you use these abbreviated argument names in your closure expression. The expected function type is used to infer the type of the shorthand argument names, and the closure’s maximum number of arguments is determined by the highest shorthand argument you use. Example: Swift
In the example above, the sayHello(to:) function takes a single argument called name of type String. The to label is used to distinguish the argument from other arguments that may have the same name. Output: Hello, GeeksforGeeks! Operator MethodsOperator methods to implement custom behavior for existing operators. Operator methods are special methods that have a symbolic operator as their name. You can define operator methods for most of the standard operators in Swift, such as the assignment operator =, the arithmetic operators +, -, *, /, and %, and the comparison operators ==, !=, >, <, >=, and <=. Example: Here’s an example with output to show you how the custom Vector2D type works with the defined operator methods: Swift
Output: vector1: (3.0, 5.0) vector2: (2.0, 4.0) sum: (5.0, 9.0) difference: (1.0, 1.0) Trailing ClosuresA trailing closure is a closure expression that is written after the function call’s parentheses, outside of the parentheses. It can be used when the closure is the only or the last argument of the function. When the closure is so long that it cannot be written inline on a single line, trailing closures are most helpful. Swift’s Array type, for instance, provides a map(_:) method that accepts a closure expression as its sole parameter. The closure delivers an alternative mapped value for each item in the array for which it is called once. By including code in the closure you supply to map(_:), you can specify the type of the mapping and the returned value. The map(_:) method returns a new array containing all of the new mapped values, in the same order as their corresponding values in the original array, after applying the specified closure to each array element. Trailing closures can make your code more concise. If the closure is the last argument of the function, you can omit the argument label and the parentheses for the closure. Example: Swift
Output: 10 In this example, the transform function takes an Int as an argument and a closure that takes an Int and returns an Int. The function returns the result of calling the closure on the input number. We can call the transform function using a trailing closure that multiplies the input number by 2. The result of the function call is 10. Capturing ValuesA closure can capture values from the surrounding context in which it is defined. This allows the closure to access and modify variables and constants outside of its own scope. To capture a value in a closure, you simply reference the value by name inside the closure. Example: Swift
Output: 2 4 6 In this example, the makeIncrementer(forIncrement:) function defines a closure called incrementer that increments a running total by a specified amount. The incrementer closure captures the runningTotal and amount variables from the surrounding context. When you call the makeIncrementer(forIncrement:) function, it returns the incrementer closure. You can then call the closure to increment the running total, the incrementByTwo constant is assigned the return value of makeIncrementer(forIncrement: 2), which is the incrementer closure. Each time you call the incrementByTwo closure, it increments the running total by 2 and returns the new value. Here is a summary of some key points about closures in Swift:
|
Reffered: https://www.geeksforgeeks.org
Swift |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |