SlideShare a Scribd company logo
1 of 16
Download to read offline
SWIFT
Higher-Order
Function
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Higher-Order Function?
•map
•filter
•reduce
•flatMap
•compactMap
•References
Higher-Order Function?
Higher-Order Function : 고차함수
1) 다른 함수를 전달인자로 받거나
2) 함수실행의 결과를 함수로 반환하는 함수
Swift에서는 대표적으로 아래의 고차함수 등을 제공합니다.
- map
- filter
- reduce
- flatMap
- compactMap
map
기존 데이터를 변형하여 새로운 컨테이너를 만들어 줍니다.
기존 데이터는 변형되지 않습니다.
map은 기존의 for-in 구문과 큰 차이가 없지만, map 사용시 다음
과 같은 이점이 있습니다.
장점
코드의 간결성
재사용 용이
컴파일러 최적화 성능 좋음
map
for-in 구문 사용 시
let numArray = [1, 3, 5, 7, 9]
var multiArray = [Int]()
for num in numArray {
multiArray.append(num * 2)
}
print(multiArray) // [2, 6, 10, 14, 18]
map 사용 시
print(multiArray) // [2, 6, 10, 14, 18]
let numArray = [1,3,5,7,9]
// 축약 미사용
let multiArray1 = numArray.map({ (number: Int) -> Int in
return number * 2
})
// 축약 사용
let multiArray2 = numArray.map { $0 * 2 }
print(multiArray1) // [2, 6, 10, 14, 18]
print(multiArray2) // [2, 6, 10, 14, 18]
filter
콜렉션 내부의 데이터를 조건에 맞는 새로운 콜렉션으로 생성
let array = ["aaa", "bbb", "cc", "dddd", "e"]
// 축약 미사용
let newArray1 = array.filter({ (value: String) -> Bool in
return value.count == 3
})
// 축약 사용
let newArray2 = array.filter { $0.count == 3 }
print(newArray1) // ["aaa", "bbb"]
print(newArray2) // ["aaa", “bbb"]
reduce
reduce는 데이터를 합쳐주기 위해 사용합니다.
기존 컨테이너에서 내부의 값들을 결합하여 새로운 값을 만듭니다.
let numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 축약 미사용
let sum1 = numberArray.reduce(0, { (first: Int, second: Int) -> Int in
return first + second
})
// 축약 사용
let sum2 = numberArray.reduce(0) { $0 + $1 }
print(sum1) // 55
print(sum2) // 55
flatMap
flatten(평평하게 하다) + map(대응하다)가 합쳐진 의미
flatMap은 map과 다르게 아래의 3가지 기능을 가지고 있습니다.
1) non-nil인 결과들을 가지는 배열을 리턴(1차 배열에서만)
2) 주어진 Sequence내의 요소들을 하나의 배열로써 리턴(2차 배
열을 1차 배열로)
3) 주어진 Optional이 not-nil인지 판단 후 unwrapping하여
closure 파라미터로 전달
flatMap
let array1 = [1, nil, 3, nil, 5, 6, 7]
// 축약 미사용
let flatMap1 = array1.flatMap() { (value: Int?) -> Int? in
return value
}
print(flatMap1) // [1, 3, 5, 6, 7]
// 축약 사용
let flatMap2 = array1.flatMap() { $0 }
print(flatMap2) // [1, 3, 5, 6, 7]
// 2차원 배열
let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]]
let flatMap3 = array2.flatMap { $0 }
print(flatMap3) // [Optional(1), Optional(2), Optional(3), nil, Optional(5),
Optional(6), nil, nil, nil]
compactMap
flatMap을 대체하기 위해서 Swift 4.1에서 나온 새로운 고차함수
1차원 배열에서 nil을 제거하고 옵셔널 바인딩을 하고 싶을 경우 사
용
단 2차원 배열을 1차원 배열로 flatten하게 만들때는 여전히
flatMap을 사용
compactMap
let array1 = [1, nil, 3, nil, 5, 6, 7]
let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]]
let compactMap1 = array1.compactMap { $0 } // 1차원 배열에 대해서 nil 요소 제거
let compactMap2 = array2.compactMap { $0 } // 2차원 배열에 대해서는 여전히 nil도 포함된다.
let compactMap3 = array2.flatMap { $0 }.compactMap { $0 } // 2차원 배열을 flatMap으로
1차원으로 변경 후 nil 요소 제거
print(compactMap1) // [1, 3, 5, 6, 7]
print(compactMap2) // [[Optional(1), Optional(2), Optional(3)], [nil,
Optional(5)], [Optional(6), nil], [nil, nil]]
print(compactMap3) // [1, 2, 3, 5, 6]
References
[1] The Swift Language Guide : https://jusung.gitbook.io/
the-swift-language-guide/
[2] 고차함수 : https://yagom.github.io/swift_basic/contents/
22_higher_order_function/
[3] Swift 고차 함수 - Map, Filter, Reduce : https://
oaksong.github.io/2018/01/20/higher-order-functions/
[4] Swift의 클로저 및 고차 함수 이해하기 : https://
academy.realm.io/kr/posts/closure-and-higher-order-
functions-of-swift/
[5] 03. 고차함수 활용 : https://edu.goorm.io/learn/lecture/
1141/야곰의-스위프트-프로그래밍/lesson/43408/고차함수
References
[6] Swift - 클로저 & 고차함수 : https://medium.com/
@ggaa96/swift-study-1-클로저-고차함수-abe199f22ad8
[7] Swift :: 고차함수 -Map, Filter, Reduce 알아보기 :
https://shark-sea.kr/entry/Swift-고차함수-Map-Filter-
Reduce-알아보기
[8] 스위프트 고차함수 swift higher-order function :
https://studyhard24.tistory.com/88
[9] Swift 클로저 및 고차 함수 (CLOSURE & HIGHER-
ORDER-FUNCTION) : https://kanghoon.tistory.com/1
[10] 고차함수 : https://blog.yagom.net/565/
References
[11] Swift의 고차함수 : https://jinunthing.tistory.com/54
[12] Swift 고차함수 사용법 : https://
usinuniverse.bitbucket.io/blog/high-order-function.html
[13] swift 기본문법 - 고차 함수(higher order function) :
https://www.zehye.kr/swift/
2020/01/16/19swift_grammer23/
[14] Swift - 고차함수(Youtube) : https://
www.youtube.com/watch?v=HmabXrK2tRo
[15] [부스트코스] iOS 프로그래밍을 위한 스위프트 기초 :
https://www.edwith.org/boostcamp_ios/lecture/11285
References
[16] [Swift] 고차함수(2) - map, flatMap, compactMap : https://
jinshine.github.io/2018/12/14/Swift/22.고차함수(2)%20-%20map,
%20flatMap,%20compactMap/
[17] Swift4.1 ) flatMap -> compactMap : https://
zeddios.tistory.com/448
[18] flatMap() 정리하기. map(), compactMap() 과의 차이 : https://
ontheswift.tistory.com/22
[19] swift. map, flatMap, compactMap : https://
mrgamza.tistory.com/606
[20] Map, FlatMap and CompactMap : https://
www.swiftbysundell.com/basics/map-flatmap-and-compactmap/
Thank you!

More Related Content

What's hot

딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04HyeonSeok Choi
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법Terry Cho
 
Functional programming
Functional programmingFunctional programming
Functional programmingssuserdcfefa
 
Why using _.chain is a mistake
Why using _.chain is a mistakeWhy using _.chain is a mistake
Why using _.chain is a mistake정기 김
 
종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍Kwang Yul Seo
 
알고리즘과 자료구조
알고리즘과 자료구조알고리즘과 자료구조
알고리즘과 자료구조영기 김
 
2012 Dm C2 04
2012 Dm C2 042012 Dm C2 04
2012 Dm C2 04seonhyung
 
말의여행
말의여행말의여행
말의여행mil23
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)Bill Kim
 
이미지프로세싱
이미지프로세싱이미지프로세싱
이미지프로세싱일규 최
 
하스켈 프로그래밍 입문 2
하스켈 프로그래밍 입문 2하스켈 프로그래밍 입문 2
하스켈 프로그래밍 입문 2Kwang Yul Seo
 
하스켈 프로그래밍 입문
하스켈 프로그래밍 입문하스켈 프로그래밍 입문
하스켈 프로그래밍 입문Kwang Yul Seo
 
Project#2말의여행 Hwp
Project#2말의여행 HwpProject#2말의여행 Hwp
Project#2말의여행 HwpKimjeongmoo
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1happychallenge
 
D2 Depth of field
D2 Depth of fieldD2 Depth of field
D2 Depth of fieldYoupyo Choi
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍Hyunsoo Jung
 

What's hot (20)

딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Why using _.chain is a mistake
Why using _.chain is a mistakeWhy using _.chain is a mistake
Why using _.chain is a mistake
 
종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍종이접기(fold) 프로그래밍
종이접기(fold) 프로그래밍
 
알고리즘과 자료구조
알고리즘과 자료구조알고리즘과 자료구조
알고리즘과 자료구조
 
2012 Dm C2 04
2012 Dm C2 042012 Dm C2 04
2012 Dm C2 04
 
말의여행
말의여행말의여행
말의여행
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
 
이미지프로세싱
이미지프로세싱이미지프로세싱
이미지프로세싱
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
하스켈 프로그래밍 입문 2
하스켈 프로그래밍 입문 2하스켈 프로그래밍 입문 2
하스켈 프로그래밍 입문 2
 
하스켈 프로그래밍 입문
하스켈 프로그래밍 입문하스켈 프로그래밍 입문
하스켈 프로그래밍 입문
 
자료구조02
자료구조02자료구조02
자료구조02
 
Project#2말의여행 Hwp
Project#2말의여행 HwpProject#2말의여행 Hwp
Project#2말의여행 Hwp
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1
 
Ch11
Ch11Ch11
Ch11
 
D2 Rain (1/2)
D2 Rain (1/2)D2 Rain (1/2)
D2 Rain (1/2)
 
D2 Depth of field
D2 Depth of fieldD2 Depth of field
D2 Depth of field
 
7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍7가지 동시성 모델 - 3장. 함수형 프로그래밍
7가지 동시성 모델 - 3장. 함수형 프로그래밍
 

Similar to [Swift] Higher order function

7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성HyeonSeok Choi
 
introduce of Hadoop map reduce
introduce of Hadoop map reduceintroduce of Hadoop map reduce
introduce of Hadoop map reduceDaeyong Shin
 
[Pgday.Seoul 2018] PostgreSQL 11 새 기능 소개
[Pgday.Seoul 2018]  PostgreSQL 11 새 기능 소개[Pgday.Seoul 2018]  PostgreSQL 11 새 기능 소개
[Pgday.Seoul 2018] PostgreSQL 11 새 기능 소개PgDay.Seoul
 
MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)
MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)
MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)주영 송
 
C Language I
C Language IC Language I
C Language ISuho Kwon
 
Deview 2019 눈발자국
Deview 2019 눈발자국Deview 2019 눈발자국
Deview 2019 눈발자국hanbeom Park
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)상욱 송
 
함수형 사고 - Functional thinking
함수형 사고 - Functional thinking함수형 사고 - Functional thinking
함수형 사고 - Functional thinking재문 심
 
파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리Booseol Shin
 
공간데이터베이스(Spatial db)
공간데이터베이스(Spatial db)공간데이터베이스(Spatial db)
공간데이터베이스(Spatial db)H.J. SIM
 

Similar to [Swift] Higher order function (13)

Go
GoGo
Go
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
introduce of Hadoop map reduce
introduce of Hadoop map reduceintroduce of Hadoop map reduce
introduce of Hadoop map reduce
 
[Pgday.Seoul 2018] PostgreSQL 11 새 기능 소개
[Pgday.Seoul 2018]  PostgreSQL 11 새 기능 소개[Pgday.Seoul 2018]  PostgreSQL 11 새 기능 소개
[Pgday.Seoul 2018] PostgreSQL 11 새 기능 소개
 
MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)
MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)
MapReduce 실행 샘플 (K-mer Counting, K-means Clustering)
 
C Language I
C Language IC Language I
C Language I
 
Deview 2019 눈발자국
Deview 2019 눈발자국Deview 2019 눈발자국
Deview 2019 눈발자국
 
Matlab guide
Matlab guideMatlab guide
Matlab guide
 
Let's Go (golang)
Let's Go (golang)Let's Go (golang)
Let's Go (golang)
 
함수형 사고 - Functional thinking
함수형 사고 - Functional thinking함수형 사고 - Functional thinking
함수형 사고 - Functional thinking
 
파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리
 
공간데이터베이스(Spatial db)
공간데이터베이스(Spatial db)공간데이터베이스(Spatial db)
공간데이터베이스(Spatial db)
 
Java8 람다
Java8 람다Java8 람다
Java8 람다
 

More from Bill Kim

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting ComparisonBill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O NotationBill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell SortBill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix SortBill Kim
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick SortBill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap SortBill Kim
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting SortBill Kim
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection SortBill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge SortBill Kim
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion SortBill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble SortBill Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary SearchBill Kim
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVLBill Kim
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search TreeBill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)Bill Kim
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary TreeBill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - TreeBill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - GraphBill Kim
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap[Swift] Data Structure - Heap
[Swift] Data Structure - HeapBill Kim
 

More from Bill Kim (20)

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O Notation
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell Sort
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix Sort
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick Sort
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap Sort
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting Sort
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection Sort
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge Sort
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion Sort
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary Search
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
 
[Swift] Data Structure - Heap
[Swift] Data Structure - Heap[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
 

[Swift] Higher order function

  • 3. Higher-Order Function? Higher-Order Function : 고차함수 1) 다른 함수를 전달인자로 받거나 2) 함수실행의 결과를 함수로 반환하는 함수 Swift에서는 대표적으로 아래의 고차함수 등을 제공합니다. - map - filter - reduce - flatMap - compactMap
  • 4. map 기존 데이터를 변형하여 새로운 컨테이너를 만들어 줍니다. 기존 데이터는 변형되지 않습니다. map은 기존의 for-in 구문과 큰 차이가 없지만, map 사용시 다음 과 같은 이점이 있습니다. 장점 코드의 간결성 재사용 용이 컴파일러 최적화 성능 좋음
  • 5. map for-in 구문 사용 시 let numArray = [1, 3, 5, 7, 9] var multiArray = [Int]() for num in numArray { multiArray.append(num * 2) } print(multiArray) // [2, 6, 10, 14, 18] map 사용 시 print(multiArray) // [2, 6, 10, 14, 18] let numArray = [1,3,5,7,9] // 축약 미사용 let multiArray1 = numArray.map({ (number: Int) -> Int in return number * 2 }) // 축약 사용 let multiArray2 = numArray.map { $0 * 2 } print(multiArray1) // [2, 6, 10, 14, 18] print(multiArray2) // [2, 6, 10, 14, 18]
  • 6. filter 콜렉션 내부의 데이터를 조건에 맞는 새로운 콜렉션으로 생성 let array = ["aaa", "bbb", "cc", "dddd", "e"] // 축약 미사용 let newArray1 = array.filter({ (value: String) -> Bool in return value.count == 3 }) // 축약 사용 let newArray2 = array.filter { $0.count == 3 } print(newArray1) // ["aaa", "bbb"] print(newArray2) // ["aaa", “bbb"]
  • 7. reduce reduce는 데이터를 합쳐주기 위해 사용합니다. 기존 컨테이너에서 내부의 값들을 결합하여 새로운 값을 만듭니다. let numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 축약 미사용 let sum1 = numberArray.reduce(0, { (first: Int, second: Int) -> Int in return first + second }) // 축약 사용 let sum2 = numberArray.reduce(0) { $0 + $1 } print(sum1) // 55 print(sum2) // 55
  • 8. flatMap flatten(평평하게 하다) + map(대응하다)가 합쳐진 의미 flatMap은 map과 다르게 아래의 3가지 기능을 가지고 있습니다. 1) non-nil인 결과들을 가지는 배열을 리턴(1차 배열에서만) 2) 주어진 Sequence내의 요소들을 하나의 배열로써 리턴(2차 배 열을 1차 배열로) 3) 주어진 Optional이 not-nil인지 판단 후 unwrapping하여 closure 파라미터로 전달
  • 9. flatMap let array1 = [1, nil, 3, nil, 5, 6, 7] // 축약 미사용 let flatMap1 = array1.flatMap() { (value: Int?) -> Int? in return value } print(flatMap1) // [1, 3, 5, 6, 7] // 축약 사용 let flatMap2 = array1.flatMap() { $0 } print(flatMap2) // [1, 3, 5, 6, 7] // 2차원 배열 let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]] let flatMap3 = array2.flatMap { $0 } print(flatMap3) // [Optional(1), Optional(2), Optional(3), nil, Optional(5), Optional(6), nil, nil, nil]
  • 10. compactMap flatMap을 대체하기 위해서 Swift 4.1에서 나온 새로운 고차함수 1차원 배열에서 nil을 제거하고 옵셔널 바인딩을 하고 싶을 경우 사 용 단 2차원 배열을 1차원 배열로 flatten하게 만들때는 여전히 flatMap을 사용
  • 11. compactMap let array1 = [1, nil, 3, nil, 5, 6, 7] let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]] let compactMap1 = array1.compactMap { $0 } // 1차원 배열에 대해서 nil 요소 제거 let compactMap2 = array2.compactMap { $0 } // 2차원 배열에 대해서는 여전히 nil도 포함된다. let compactMap3 = array2.flatMap { $0 }.compactMap { $0 } // 2차원 배열을 flatMap으로 1차원으로 변경 후 nil 요소 제거 print(compactMap1) // [1, 3, 5, 6, 7] print(compactMap2) // [[Optional(1), Optional(2), Optional(3)], [nil, Optional(5)], [Optional(6), nil], [nil, nil]] print(compactMap3) // [1, 2, 3, 5, 6]
  • 12. References [1] The Swift Language Guide : https://jusung.gitbook.io/ the-swift-language-guide/ [2] 고차함수 : https://yagom.github.io/swift_basic/contents/ 22_higher_order_function/ [3] Swift 고차 함수 - Map, Filter, Reduce : https:// oaksong.github.io/2018/01/20/higher-order-functions/ [4] Swift의 클로저 및 고차 함수 이해하기 : https:// academy.realm.io/kr/posts/closure-and-higher-order- functions-of-swift/ [5] 03. 고차함수 활용 : https://edu.goorm.io/learn/lecture/ 1141/야곰의-스위프트-프로그래밍/lesson/43408/고차함수
  • 13. References [6] Swift - 클로저 & 고차함수 : https://medium.com/ @ggaa96/swift-study-1-클로저-고차함수-abe199f22ad8 [7] Swift :: 고차함수 -Map, Filter, Reduce 알아보기 : https://shark-sea.kr/entry/Swift-고차함수-Map-Filter- Reduce-알아보기 [8] 스위프트 고차함수 swift higher-order function : https://studyhard24.tistory.com/88 [9] Swift 클로저 및 고차 함수 (CLOSURE & HIGHER- ORDER-FUNCTION) : https://kanghoon.tistory.com/1 [10] 고차함수 : https://blog.yagom.net/565/
  • 14. References [11] Swift의 고차함수 : https://jinunthing.tistory.com/54 [12] Swift 고차함수 사용법 : https:// usinuniverse.bitbucket.io/blog/high-order-function.html [13] swift 기본문법 - 고차 함수(higher order function) : https://www.zehye.kr/swift/ 2020/01/16/19swift_grammer23/ [14] Swift - 고차함수(Youtube) : https:// www.youtube.com/watch?v=HmabXrK2tRo [15] [부스트코스] iOS 프로그래밍을 위한 스위프트 기초 : https://www.edwith.org/boostcamp_ios/lecture/11285
  • 15. References [16] [Swift] 고차함수(2) - map, flatMap, compactMap : https:// jinshine.github.io/2018/12/14/Swift/22.고차함수(2)%20-%20map, %20flatMap,%20compactMap/ [17] Swift4.1 ) flatMap -> compactMap : https:// zeddios.tistory.com/448 [18] flatMap() 정리하기. map(), compactMap() 과의 차이 : https:// ontheswift.tistory.com/22 [19] swift. map, flatMap, compactMap : https:// mrgamza.tistory.com/606 [20] Map, FlatMap and CompactMap : https:// www.swiftbysundell.com/basics/map-flatmap-and-compactmap/