스위프트 문법 : Closures (영)

김영채 (Kevin)·2021년 1월 15일
0

iOS & Swift

목록 보기
29/107
  • Anonymous functions
func calculator(n1: Int, n2: Int, operation: (Int, Int)->Int{
	return operation(n1,n2)
}

func add(no1: Int, no2: Int)->Int{
	return no1+no2
}

func multiply(no1: Int, no2: Int)->Int{
	return no1 * no2
}

calculator(n1: 2, n2: 3, operation: add)    // 5
calculator(n1: 2, n2: 3, operation: multiply)  // 6

//The usual way how we would pass functions as parameters
  • How to write a closure?


→ The usual way we would define a function (top)

→ How to write a closure : remove the keyword func and also remove the function's name. Then, move the curly brace to the front

//passing a closure as an input parameter
func calculator(n1: Int, n2: Int, operation: (Int, Int)->Int{
	return operation(n1,n2)
}

calculator(n1: 2, n2: 3, operation: {(no1: Int, no2: Int)->Int in
	return no1 * no2
})    // 6

//You don't always have to write the data types -> Type inference supported
//Return type also can be deleted.
calculator(n1: 2, n2: 3, operation: {(no1, no2) in
	return no1 * no2
}) 

//$0 refers to the first parameter, $1 refers to the second
let result = calculator(n1: 2, n2: 3, operation: { $0 * $1 })
let result = calculator(n1: 2, n2: 3) { $0 * $1 } //Trailing Closure
let array = [6,2,3,9,4,1]

array.map( { (n1) in return n1+1 } )
//or
print(array.map{$0 + $1})
//7,3,4,10,5,2

→ What if we want to convert the array to a String type array?

let stringArray = array.map { "\($0)" }
print(stringArray)
//"6", "2", "3" ..etc

→ Overall, we can see the use of Closures is a very succinct way of writing code.

profile
맛있는 iOS 프로그래밍

0개의 댓글