공식문서(번역) https://jusung.gitbook.io/the-swift-language-guide/language-guide/07-closures
아주 정확히는 함수는 Closure의 한가지 타입
Closure는 크게 3가지 타입이 있음
전역 함수(Global) : 이름이 있고 어떤 값도 캡쳐하지 않는 클로저
중첩 함수(Nested) : 이름이 있고 관련한 함수로 부터 값을 캡쳐 할 수 있는 클로저
클로저 표현(Closure Expression) : 경량화 된 문법으로 쓰여지고 관련된 문맥(context)으로부터 값을 캡쳐할 수 있는 이름이 없는 클로저
함수처럼 기능을 수행하는 코드블록, 함수와 달리 이름이 없다.
함수와 클로저 둘 다 First Class Type(일급객체)이다.
-> 변수에 할당할 수 있고, 인자로 받을 수 있으며, 리턴할 수 있다.
자바스크립트의 익명함수와 비슷하기도 하다
-> JavaScript의 Closure와의 차이점
https://medium.com/ios-development-with-swift/%ED%81%B4%EB%A1%9C%EC%A0%80-closure-swift-vs-javascript-d3a3a3933e18
비동기적으로 작동하는 경우 어떤 작업이 완료되었을 때 수행시킬 때 클로저를 많이 씀(콜백함수같은 느낌?)
함수를 다루는 함수를 말함. 함수의 인수를 함수로 받을 수 있고 함수를 반환하는 함수를 말함. 이때 넘기는 함수를 클로저로 씀.
var multiplyClosure: (Int, Int) -> Int = { a, b in
return a * b
}
multiplyClosure(4, 2)
func operateToNum(a:Int, b:Int, operation:(Int, Int) -> Int) -> Int{
let result = operation(a, b)
return result
}
operateToNum(a: 4, b: 2, operation: multiplyClosure)
var addClosure : (Int, Int) -> Int = { a, b in
return a + b
}
operateToNum(a: 4, b: 2, operation: addClosure)
operateToNum(a: 4, b: 2) {a, b in
return a / b
}
//codeForEveryoneJoonwon+02@gmail.com
let voidClosure: () -> Void = {
print("iOS!")
}
voidClosure()
//Capturing Values
var count = 0
let incrementer = {
count += 1
}
incrementer()
incrementer()
incrementer()
incrementer()
count
{ (parameters) -> returnType in
statements
}
let simpleClosure = {
}
simpleClosure()
let blockClosure = {
print("Hello, Closure")
}
blockClosure()
let inputParamClosure: (String) -> Void = { name in
print("My name is \(name)!")
}
inputParamClosure("Dzeko")
let returnClosure: (String) -> String = {name in
let stock = "Stockholm syndrome is composed by \(name)"
return stock
}
let memo = returnClosure("Matthew")
print(memo)
func simpleFunction(choSimpleClosure: () -> Void) {
print("함수에서 호출이 되었다.")
choSimpleClosure()
}
simpleFunction(choSimpleClosure: {
print("Hello!")
})
func trailClosure(message:String, verySimpleClosure: () -> Void){
print("Called by Func, and message is \(message)")
verySimpleClosure()
}
trailClosure(message: "어허!", verySimpleClosure: {print("넵")})
trailClosure(message: "어허!") {
print("넵")
}
// 같은 코드가 된다