[SWIFT] Let's understand closures!

This time, we learned about closures, so we will output them.

What is a closure?

*** Closures are reusable chunks of processing. *** *** Functions are a type of closure, so they have many common uses. To use the function, it was necessary to define it with the "func" keyword, but closures can be defined as closure expressions.

*** Click here to review functions !! *** Let's understand the function! (Https://qiita.com/syunta061689/items/77e8aa76070a734f1b4d)

The basic definition method is as follows.

qiita.rbvar


{(Argument name 1: Type,Argument name 2: Type...) ->Return type in
Statement executed at closure execution
Return the return value with a return statement if necessary
}

Let's look at a simple example next.

qiita.rbvar


let double = {(x:Int) -> Int in

return x * 5

}
double(5) //25

The description of the argument and return type is the same as for a function, but the return type and statement are separated by the in keyword. In the above example, a closure that takes one Int type argument and returns an Int type return value that is multiplied by 5 is defined and executed.

Function as a closure

qiita.rbvar


func rectangleArea(height:Int,width:Int) -> Int {
 let result = height*width
 return result //Return the calculation result

}

let area = rectangleArea(height: 5,width: 6) //30

In the above example, the variable type is clearly determined as Int-> Int, and the result return of the calculation result is executed and the return value is returned.

Array type as a closure

The following is a pattern to return an array or dictionary:

*** Click here to review the Array type !! *** Let's understand the Array type! (Https://qiita.com/syunta061689/items/89e549f4a3254f635ce1)

Let's look at a simple example.

qiita.rbvar


func a(num: [Int] -> [Int] { //Returns an array of type Int
    print num
}
 
func b(strings: [String: Int]) -> [String: Int]{ //Allows you to receive a dictionary whose key is a String type and whose value is an Int type.
    print strings
}

let test = a(num:0,1,2) 
let test1 = b(String:[Chimpanzee:0,gorilla:1]) 

print(a)//[0,1,2]
print(b) //[Chimpanzee:0,gorilla:1]

Finally

This time, I have summarized the basics of closures. However, the content described this time is the foundation of the basics, the closure is deep and there is a complicated writing style, so I will continue to understand it firmly in the future.

Recommended Posts

Let's understand closures!
Let's understand the function!
Let's understand the if statement!
Let's understand the guard statement!
Let's understand the for-in statement!
Let's understand the switch statement!
Let's understand the Array (Element) type!
Let's understand the Optional (Wrapped) type!
Understand Docker
Understand DI
[Swift vs Java] Let's understand static and final