Closure
- 함수처럼 기능을 수행하는 코드 블록
- 이름이 없는 메서드
- 함수는 Closure의 한 가지 타입
- Closure는 크게 3가지 타입이 있음
1. Global 함수
2. Nested 함수
3. Closure Expressions
First Class Type
- 변수에 할당할 수 있다
- 인자로 받을 수 있다
- 리턴할 수 있다
import UIKit
// Closure
// { (param) -> return type {
// statement
// }
var Closure: (Int, Int) -> Int = { a, b in
return a * b
}
let result = Closure(5, 2)
func operate(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int {
let result = operation(a, b)
return result
}
operate(a: 5, b: 3, operation: Closure)
var addOperate: (Int, Int) -> Int = { a, b in
return a + b
}
operate(a: 10, b: 3, operation: addOperate)
operate(a: 10, b: 2) { a, b in
return a / b
}
let voidClosure: () -> Void = {
print("Void Closure")
}
voidClosure()
// Capturing Value
var count = 0
let incrementer = {
count += 1
}
incrementer()
incrementer()
count
// 간단한 클로저
let simpleClosure = {
}
simpleClosure()
// 코드 블럭을 구현한 클로저
let simpleClosure1 = {
print("Hello")
}
simpleClosure1()
// 인풋 파라미터를 받는 클로저
let simpleClosure2: (String) -> Void = { name in
print("my name is \(name)")
}
simpleClosure2("khon")
// 값을 return 하는 클로저
let simpleClosure3: (String) -> String = { name in
let message = "Hello my name is \(name)"
return message
}
let result1 = simpleClosure3("khon")
print(result1)
// 클로저를 파라미터로 받는 함수 구현
func someSimpleClosure(SimpleClosure: () -> Void) {
print("함수에서 호출")
SimpleClosure()
}
someSimpleClosure(SimpleClosure: {
print("Closure")
})
// Trailing Closure
// 마지막 클로저는 생략 가능
func SomeSimpleClosure(message: String, SimpleClosure: () -> Void) {
print("Message is \(message)")
SimpleClosure()
}
// 생략 전 코드
// SomeSimpleClosure(message: "Hi", SimpleClosure: {
// print("it's Closure")
// })
// 생략 후 코드
SomeSimpleClosure(message: "Hi") {
print("it's Closure")
}
'Swift > 문법' 카테고리의 다른 글
Property / Method (0) | 2021.03.04 |
---|---|
Class / 상속 / 생성자 (0) | 2021.03.03 |
Structure / Protocol (0) | 2021.03.02 |
Array / Dictionary / Set (0) | 2021.03.01 |
Function / Optional (0) | 2021.02.26 |