[TIL] Swift - 클로저(Closure) 문법 정리하기

jeongmuyamette·2025년 1월 17일

TIL

목록 보기
29/72
post-thumbnail

📝 오늘 배운 내용

오늘은 Swift의 클로저(Closure) 문법에 대해 정리해보았습니다. 클로저는 Swift에서 매우 중요한 개념이며, 특히 iOS 개발에서 자주 사용되는 문법입니다.

🤔 클로저란?

클로저는 코드 블록을 하나의 독립적인 기능 단위로 사용할 수 있게 해주는 문법입니다. 함수는 사실 클로저의 특별한 한 형태라고 볼 수 있습니다.

기본 클로저 문법

let simpleClosure = { (parameters) -> ReturnType in
    // 코드
}

클로저 예시와 축약 과정

1️⃣ 기본형 클로저

let numbers = [1, 2, 3, 4, 5]
let sortedNumbers = numbers.sorted(by: { (num1: Int, num2: Int) -> Bool in
    return num1 > num2
})

2️⃣ 반환 타입 생략

let sortedNumbers = numbers.sorted(by: { (num1: Int, num2: Int) in
    return num1 > num2
})

3️⃣ 파라미터 타입 생략

let sortedNumbers = numbers.sorted(by: { num1, num2 in
    return num1 > num2
})

4️⃣ return 생략 (단일 표현식)

let sortedNumbers = numbers.sorted(by: { num1, num2 in num1 > num2 })

5️⃣ 축약 인자 이름 사용

let sortedNumbers = numbers.sorted(by: { $0 > $1 })

6️⃣ 연산자 함수

let sortedNumbers = numbers.sorted(by: >)

🌟 클로저의 캡처

클로저는 자신이 정의된 컨텍스트의 상수와 변수를 캡처할 수 있습니다.

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    let incrementer: () -> Int = {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

let incrementByTwo = makeIncrementer(forIncrement: 2)
print(incrementByTwo()) // 2
print(incrementByTwo()) // 4
print(incrementByTwo()) // 6

💡 오늘의 깨달은 점

  • 클로저는 함수형 프로그래밍의 핵심 요소
  • 코드를 더 간결하고 읽기 쉽게 만들 수 있음
  • 특히 비동기 프로그래밍에서 매우 유용함
  • 축약 문법을 통해 코드를 더 간결하게 작성할 수 있음

🔍 참고자료

  • Swift 공식 문서: Closures
  • Apple Developer Documentation

✏️ 다음에 더 공부할 내용

  • Escaping Closure
  • AutoClosure
  • 클로저와 메모리 관리
  • 클로저의 강한 참조 순환

0개의 댓글