[Swift] Closure

Dzeko·2021년 8월 2일

Swift 기본

목록 보기
17/20
post-thumbnail

Closure란?

공식문서(번역) 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

많이 쓰는 경우 1 - Completion Block

비동기적으로 작동하는 경우 어떤 작업이 완료되었을 때 수행시킬 때 클로저를 많이 씀(콜백함수같은 느낌?)

많이 쓰는 경우 2 - Higher Order Functions(고계함수)

함수를 다루는 함수를 말함. 함수의 인수를 함수로 받을 수 있고 함수를 반환하는 함수를 말함. 이때 넘기는 함수를 클로저로 씀.


var multiplyClosure: (Int, Int) -> Int = { a, b in
    return a * b
}
multiplyClosure(4, 2)

closure를 parameter로 받는 함수

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

Closure Expression Syntax

{ (parameters) -> returnType in
    statements
}

예시

1. 간단한 Closure

let simpleClosure = {
    
}
simpleClosure()

2. 코드블록을 구현한 Closure

let blockClosure = {
    print("Hello, Closure")
}
blockClosure()

3. 인풋 파라미터를 받는 Closure

let inputParamClosure: (String) -> Void = { name in
        print("My name is \(name)!")
}
inputParamClosure("Dzeko")

4. 값을 리턴하는 Closure

let returnClosure: (String) -> String = {name in
    let stock = "Stockholm syndrome is composed by \(name)"
    return stock
}
let memo = returnClosure("Matthew")
print(memo)

5. Closure를 파라미터로 받는 함수 구현

func simpleFunction(choSimpleClosure: () -> Void) {
    print("함수에서 호출이 되었다.")
    choSimpleClosure()
}
simpleFunction(choSimpleClosure: {
    print("Hello!")
})

6. Trailing Closure(후행클로저) 인자가 여러개이고 마지막 인자가 클로저인 경우 생략가능함

func trailClosure(message:String, verySimpleClosure: () -> Void){
    print("Called by Func, and message is \(message)")
    verySimpleClosure()
}

trailClosure(message: "어허!", verySimpleClosure: {print("넵")})
trailClosure(message: "어허!") {
    print("넵")
}
// 같은 코드가 된다

0개의 댓글