티스토리 뷰
Closure (클로저)
Closures 종류
- Name Closures :: Function, Nested Function
- Unnamed Closures :: Anonymous Function (우리가 부르게 될 Closures)
Closures 선언
{ (parameters) -> ReturnType/*Closure Head*/ in
statements
/*Closure Body*/
}
// 간단한 Closure
{ statements }
Closures 예시
let c = { print("Hello, World") }
// Closure는 이름이 없는 함수인데 c라고 이름을붙인 것
c() // Hello, World
let c2 = { (str: String) -> String in
return "Hello, \(str)"
}
let result = c2("Closure")
print(result)
// Closure를 호출할 때는 Argument Label를 사용하지 않는다.
typealias SimpleStringClosure = (String) -> String
func perform(closure: SimpleStringClosure) {
print(closure("iOS"))
}
perform(closure: c2) // Hello, iOS
perform(closure: { (str: String) -> String in
return "Hi, \(str)"
})
// 이해해보기
let products = [
"MacBook Air", "MacBook Pro",
"iMac", "iMac Pro", "Mac Pro", "Mac mini",
"iPad Pro", "iPad", "iPad mini",
"iPhone Xs", "iPhone Xr", "iPhone 8", "iPhone 7",
"AirPods",
"Apple Watch Series 4", "Apple Watch Nike+"
]
var proModels = products.filter({ (name: String) -> Bool
in
return name.contains("Pro")
})
print(proModels)
// ["MacBook Pro", "iMac Pro", "Mac Pro", "iPad Pro"]
print(proModels.sorted())
// ["Mac Pro", "MacBook Pro", "iMac Pro", "iPad Pro"]
products.sorted(by: { (lhs: String, rhs: String) -> Bool
in
return lhs.caseInsensitiveCompare(rhs)
== .orderedAscending
})
print(proModels)
// ["MacBook Pro", "iMac Pro", "Mac Pro", "iPad Pro"]
print("Start")
DispatchQueue.main.asyncAfter(deadline: .now() + 5 , execute: {
print("End") // Start보다 5초 후 출력
})
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
print("End") // 문법 최적화, Syntax Optimization
}
Closures 예시2
// 코드의 블럭
// 일급 시민(first-citizen)
// 변수, 상수 등으로 저장, 전달인자로 전달이 가능
// 함수 : 이름이 있는 클로저
// MARK: - 정의
/*
{ (매개변수 목록) -> 반환타입 in
실행코드
}
*/
// 함수를 사용한다면
func sumFunction(a: Int, b: Int) -> Int {
return a + b
}
var sumResult: Int = sumFunction(a: 1, b: 2)
print(sumResult) // 3
// 클로저의 사용
var sum: (Int, Int) -> Int = { (a: Int, b: Int) in
return a + b
}
sumResult = sum(1,2)
print(sumResult) // 3
// 함수는 클로저의 일종이므로
// sum 변수에는 당연히 함수도 할당할 수 있습니다.
sum = sumFunction(a:b:)
sumResult = sum(1,2)
print(sumResult) // 3
// MARK: - 함수의 전달인자로서의 클로저
let add: (Int, Int) -> Int
add = { (a: Int, b: Int) -> Int in
return a + b
}
let substract: (Int, Int) -> Int
substract = { (a: Int, b: Int) -> Int in
return a - b
}
let divide: (Int, Int) -> Int
divide = { (a: Int, b: Int) -> Int in
return a / b
}
func calculate(a: Int, b: Int, method: (Int, Int) -> Int) -> Int {
return method(a,b)
}
var calculated: Int
calculated = calculate(a: 50, b: 10, method: add)
print(calculated) // 60
calculated = calculate(a: 50, b: 10, method: substract)
print(calculated) // 40
calculated = calculate(a: 50, b: 10, method: divide)
print(calculated) // 5
calculated = calculate(a: 50, b: 10, method: { (left: Int, right: Int) -> Int in
return left * right
})
print(calculated) // 500
'Swift' 카테고리의 다른 글
[Swift] Collection - Array, Dictionary, Set (0) | 2021.03.09 |
---|---|
[Swift] Structures and Classes (0) | 2021.03.08 |
[Swift] Enumerations (열거형) (0) | 2021.03.03 |
[Swift] Functions (함수) (0) | 2021.02.20 |
[Swift] Optionals (옵셔널) (0) | 2021.02.18 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 옵셔널
- RawValues
- optional
- 결합성
- playground
- datatypes
- 객체지향 생활체조
- 훈련법
- enumerations
- continue
- 삼항연산자
- 오토레이아웃
- swift
- scope
- 비트연산자
- 전산구문 기초용어
- overflow
- Constants
- 구문이름표
- 흐름제어구문
- iOS View Life Cycle
- 산술연산자
- labeled
- 세자리수마다 콤마넣기
- Functions
- 반복문
- 오버플로우연산자
- conditional
- 범위연산자
- variables
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함