스위프트 문법 : Closures (영)
- 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.
Author And Source
이 문제에 관하여(스위프트 문법 : Closures (영)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kevinkim2586/스위프트-문법-Closures-영저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)