SlideShare a Scribd company logo
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

PPTX
Pyconkr2019 features for using python like matlab
PDF
ES6 for Node.js Study 3주차
PDF
밑바닥부터시작하는딥러닝 Ch05
PDF
밑바닥부터시작하는딥러닝 Ch05
PDF
Alphago at a Glance
PPTX
R 기본-데이타형 소개
Pyconkr2019 features for using python like matlab
ES6 for Node.js Study 3주차
밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05
Alphago at a Glance
R 기본-데이타형 소개

What's hot (20)

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

Similar to [Swift] Higher order function (20)

PDF
키트웍스_발표자료_김경수functional_programming240920.pdf
PDF
Haskell study 5
PDF
[Swift] Collection types
PPTX
하스켈 성능 튜닝 2
PPTX
Functional programming
PPTX
함수형 사고 - Functional thinking
DOCX
이산치수학 Project6
PPTX
하스켈 성능 튜닝
PDF
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
PPTX
파이썬 Collections 모듈 이해하기
PDF
2012 Ds C2 06
PPTX
세미나
PPTX
Feel functional
PDF
하스켈 모나드
PDF
쏙 알고스터디 01
PPT
Swift basic operators-controlflow
PDF
Haskell study 4
PDF
Backtracking [ICPC Sinchon]
PPTX
Swift2
KEY
Ruby 2 array_hash
키트웍스_발표자료_김경수functional_programming240920.pdf
Haskell study 5
[Swift] Collection types
하스켈 성능 튜닝 2
Functional programming
함수형 사고 - Functional thinking
이산치수학 Project6
하스켈 성능 튜닝
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
파이썬 Collections 모듈 이해하기
2012 Ds C2 06
세미나
Feel functional
하스켈 모나드
쏙 알고스터디 01
Swift basic operators-controlflow
Haskell study 4
Backtracking [ICPC Sinchon]
Swift2
Ruby 2 array_hash
Ad

More from Bill Kim (20)

PDF
[Algorithm] Sorting Comparison
PDF
[Algorithm] Big O Notation
PDF
[Algorithm] Shell Sort
PDF
[Algorithm] Radix Sort
PDF
[Algorithm] Quick Sort
PDF
[Algorithm] Heap Sort
PDF
[Algorithm] Counting Sort
PDF
[Algorithm] Selection Sort
PDF
[Algorithm] Merge Sort
PDF
[Algorithm] Insertion Sort
PDF
[Algorithm] Bubble Sort
PDF
[Algorithm] Binary Search
PDF
[Swift] Data Structure - AVL
PDF
[Swift] Data Structure - Binary Search Tree
PDF
[Swift] Data Structure - Graph(BFS)
PDF
[Swift] Data Structure - Graph(DFS)
PDF
[Swift] Data Structure - Binary Tree
PDF
[Swift] Data Structure - Tree
PDF
[Swift] Data Structure - Graph
PDF
[Swift] Data Structure - Heap
[Algorithm] Sorting Comparison
[Algorithm] Big O Notation
[Algorithm] Shell Sort
[Algorithm] Radix Sort
[Algorithm] Quick Sort
[Algorithm] Heap Sort
[Algorithm] Counting Sort
[Algorithm] Selection Sort
[Algorithm] Merge Sort
[Algorithm] Insertion Sort
[Algorithm] Bubble Sort
[Algorithm] Binary Search
[Swift] Data Structure - AVL
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Tree
[Swift] Data Structure - Graph
[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/