Swift 기본 고차함수(HOF; Higher Order Function) 에 대해알아보고 간단히 구현해보자.
고차함수란, 함수를 인자로 전달받거나 함수를 결과로 반환하는 함수를 의미한다.
보통 Swift에서 고차함수라고 한다면, forEach, map, filter, reduce처럼 Stream Data을 다루는 이야기가 많다.
1편에서는 위의 4가지 고차함수가 뭔지 알아보고, 한 가지를 직접 구현해볼 예정이다!
2편에는 contains, min, max도 사실 고차함수의 형태였다는 사실과 flatMap, compactMap, allSatisfy, partition 에 대해 알아보자.
forEach
func forEach(_ body: (Self.Element) throws -> Void) rethrows
단순히 Sequence의 Element를 순회한다.
for-in 구분과 다른 점은 continue, break 등의 구문을 사용하지 못한다는 점이다.
var numbers = [30, 40, 20, 30, 30, 60, 10]
numbers.forEach {
print($0)
}
// 30
// 40
// 20
// 30
// 30
// 60
// 10
map
func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
forEach 처럼 Element를 순회하면서 return 값을 받는다.
Generic으로 정의된 타입이기 때문에 모든 순회의 리턴값이 동일하다면 어떠한 타입으로 변환해도 상관없다.
var numbers = [30, 40, 20, 30, 30, 60, 10]
numbers.map {
$0.isMultiple(of: 3) // 3의 배수라면 true를 반환한다.
}
// [true, false, false, true, true, true, false]
filter
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
inIncluded에서 Bool 값이 true 전달된 Element만을 배열에 담아 반환한다.
var numbers = [30, 40, 20, 30, 30, 60, 10]
numbers.filter {
$0.isMultiple(of: 3)
}
// [30, 30, 30, 60]
reduce
func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result
초기값을 인자로 받아 순회를 시작한다.
nextPartialResult의 Result 값은 다음 순회의 Result 인자가 된다.
let numbers = [1,2,3,4,5]
numbers.reduce(0) {
return $0 + $1
}
// 15
고차함수 map 직접 만들기
Closure, Extension과 Generic에 대한 이해가 필요하다.
extension Collection {
func customMap<T>(_ closure: (Element) -> T) -> [T] {
var returnValue: [T] = [] // 최종 Return 값
var currentIndex: Index = self.startIndex // 순회를 위한 Index 값
while currentIndex != self.endIndex { // 마지막 Index까지 반복
// 로직이 수행될 closure에 Element를 전달하고 반환된 값을 배열에 추가
returnValue.append(closure(self[currentIndex]))
// 다음 Index 저장
currentIndex = self.index(after: currentIndex)
}
return returnValue
}
}
다음편
[Swift] HOF(Higher Order Function) (2)
1편에 이어 [Swift] HOF(Higher Order Function) (1) Swift 기본 고차함수(HOF; Higher Order Function) 에 대해알아보고 간단히 구현해보자. 고차함수란, 함수를 인자로 전달받거나 함수를 결과로 반환하는 함수..
littlemoom.tistory.com
Reference
https://www.swiftbysundell.com/tips/picking-between-for-and-for-each/
https://developer.apple.com/documentation/swift/array
https://developer.apple.com/documentation/swift/sequence
'iOS > Swift' 카테고리의 다른 글
[Swift] Protocol Composition (0) | 2024.01.09 |
---|---|
[Swift] HOF(Higher Order Function) (2) (0) | 2022.08.03 |
[Swift] await, async (0) | 2022.06.30 |
[Swift] 클래스 (0) | 2022.06.24 |
[Swift] 구조체 (0) | 2022.06.16 |