본문 바로가기
#모바일 [Mobile]/iOS

[iOS] Swift 고차 함수 (Higher-order function)

by cy_mos 2020. 6. 5.
반응형
카테고리 (Category) 작성 날짜 (Write Date) 최근 수정 날자 (Recent Write Date) 작성자 (Writer)
iOS 2020-06-05 15:33 2021.12.02. 23:34 Dev.Yang

 

고차 함수(Higher-order function)는 ‘다른 함수를 전달 인자로 받거나 함수 실행의 결과를 함수로 반환하는 함수’를 뜻합니다. 스위프트의 함수는 일급 시민이기 때문에 함수의 전달 인자로 함수를 전달할 수 있으며, 함수를 결괏값으로 반환할 수 있습니다. 또한, Swift의 대표적인 고차 함수로는 filter, reduce, map, compactMap 등이 있습니다. 또한, map, filter, reduce 함수는 스위프트 표준 라이브러리의 컨테이너 타입(Array, Set, Dictionary 등)에 구현되어 있습니다


🛠 Map

func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

 

[영문]

Returns an array containing the results of mapping the given closure over the sequence’s elements.

 

[국문]

순차적인 원소들에 대해서 주어진 클로저 (Closure)를 사용하여 조건에 맞는 원소를 맵핑(Mapping)하여 결과가 포함 된 배열을 반환합니다.

 

⏱ Time Complexity: O(n), where n is the length of the sequence.

 

📚 Example Source Code

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]

🛠 Filter

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

 

[영문]

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

 

[국문]

주어진 연산 조건에 만족하는 순차적인 원소들을 포함하는 배열을 반환합니다.

 

 Time Complexity: O(n), where n is the length of the sequence.

 

📚 Example Source Code

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

🛠 Reduce

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

 

[영문]

Returns the result of combining the elements of the sequence using the given closure.

 

[국문]

주어진 클로저 (Closure)를 사용하여 순차적인 원소들을 하나의 결과로 만들어 반한합니다.

 

 Complexity: O(n), where n is the length of the sequence.

 

📚 Example Source Code

let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
    x + y
})
// numberSum == 10

🛠 FlatMap

func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

 

[영문]

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

 

[국문]

여러개의 배열을 하나의 배열로 만들어 새로운 배열로 반환합니다.

 

⏱ Time Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.

 

📚 Example Source Code

let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

🛠 CompactMap

func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

 

[영문]

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

 

[국문]

일련의 순서에 대한 각각의 원소들에 대해서 변형하고자 하는 자료형이 주어졌을 때 nil이 아닌 값을 결과로 가진 변형 된 자료형에 대한 배열을 반환하는 고차함수의 일종입니다.

 

⏱ Time Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.

 

📚 Example Source Code

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]

🚀 REFERENCE

 

고차 함수 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 둘러보기로 가기 검색하러 가기 고차 함수(高次函數, higher-order function)는 수학과 컴퓨터 과학에서 적어도 다음 중 하나를 수행하는 함수이다.[1][2][3] 하나 이상�

ko.wikipedia.org

 

iOS 프로그래밍을 위한 스위프트 기초

부스트코스 무료 강의

www.boostcourse.org

반응형

댓글