Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

Olive Study Room

[Swift] 고차함수(map, filter, reduce) 본문

Coding/iOS

[Swift] 고차함수(map, filter, reduce)

Olive Dev 2021. 6. 7. 16:12
더보기

매 프로젝트에서 사용은 해왔지만 영문도 모르고 받아 적기만 했던 고차함수.

한번 정리해보자!

고차함수란?

매개변수로 함수를 받거나 함수를 반환하는 함수
  • map, filter, reduce 등이 있다.
  • 위 함수는 swift 표준 라이브러리에 속한다.

 

1. map(_:) 

시퀀스의 요소를 통해 지정된 클로저를 맵핑한 결과가 포함된 배열을 리턴한다.

 

Declaration

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

Parameters

transform : 맵핑 클로저. 파라미터처럼 이 시퀀스의 요소에 접근하고, 같거나 다른 타입의 변형된 값을 리턴한다.

 

* 클로저 내에 생략할 수 있는 값

let text: [Int] = [1, 2, 3, 4]

1. 생략 없음
print(text.map({(number: Int) -> String in
    return "\(number)"
}))

2. 반환 타입 생략
print(text.map({(number: Int) in
    return "\(number)"
}))

3. 반환타입, 변수 생략
print(text.map({ "\($0)" }))

 


2. filter(_:) 

지정된 predicate를 만족하는 시퀀스의 요소를 순서대로 포함하는 배열을 리턴한다.

 

Declaration

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

Parameters

isIncluded : 그 argument와 같은 시퀀스의 요소를 갖고, 요소가 반환된 배열에 포함될 때 bool값을 리턴한다.

 

Example

let text: [Int] = [1, 2, 3, 4]
print(text) // [1, 2, 3, 4]
print(text.filter({(value: Int) -> Bool in
    return value % 2 == 1
}))
print(text.filter({ $0 % 2 == 1}))

 


3. reduce(_:) 

지정된 클로저를 사용하는 시퀀스의 요소를 종합한 결과를 리턴한다.

 

Declaration

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

Parameters

initialResult : 초기 누적 값으로 사용할 값. 초기 결과는 클로저가 실행되면 nextPartialResult의 처음에 지나쳐진다.

nextPartialResult : 누적 값과 시퀀스의 요소를 새 누적값으로 결합하는 클로저로, nextPartialResult 클로저의 다음 호출에서 사용하거나 호출자에게 반환한다. 

-> 번역이라 이상하지만, InitialResult는 초기값이고 컨테이너 요소는 nextPartialResult으로 초기값과 순차적으로 클로저를 실행한다.

Example

let text: [Int] = [1, 2, 3, 4]
var sum: Int = text.reduce(0, {(result: Int, next: Int) -> Int in
    print(result, next )
    return result + next
})
//0 1
//1 2
//3 3
//6 4
var substract: Int = text.reduce(0, {(result: Int, next: Int) -> Int in
    print(result, next)
    return result - next
})
//0 1
//-1 2
//-3 3
//-6 4

var multi: Int = text.reduce(1, {(result: Int, next: Int) -> Int in
    print(result, next)
    return result*next
})
//1 1
//1 2
//2 3
//6 4

var multi2: Int = text.reduce(1, { $0 * $1 })
print(multi2)
// 24

 

 

 

'Coding > iOS' 카테고리의 다른 글

[Swift] Map VS compactMap VS flatMap  (0) 2021.06.23
[Swift] Control Flow  (0) 2021.06.17
[Swift] components(separatedBy:) & split  (0) 2021.06.07
[Swift] RawRepresentable  (0) 2021.05.01
[iOS] UISearchBar - 검색기능 구현하기 (1) 필수항목  (0) 2021.04.30
Comments