프로그래밍/기초
[Lv1 - 13] 고차함수(Higher Order Functions)
시르베어
2025. 7. 21. 17:03
https://github.com/JeaSungLEE/iOSInterviewquestions
Swift의 고차 함수(Higher-Order Functions)에 대해 설명해주세요.
- map과 flatMap의 차이점은 무엇인가요?
- filter, reduce 함수는 어떤 경우에 사용하나요?
- compactMap은 어떤 역할을 하나요?
고차함수(Higher Order Functions)
다른 함수를 인자로 받거나, 함수를 반환하는 함수를 고차 함수라고합니다.
map
배열의 각 요소에 클로저로 전달된 함수를 적용한 새로운 배열을 반환합니다.
let functionA = { (num: Int) -> Int in
return num + num
}
let numbers: [Int] = [1, 2, 3, 4, 5, 6]
let result: [Int] = numbers.map(functionA) // 함수를 인자로 받음
print(result) // [2, 4, 6, 8, 10, 12]
flatMap
각 요소에 클로저로 전달된 함수를 적용하여 새로운 배열을 반환합니다. 이때 반환되는 배열은 1차원 배열로 생성됩니다.
let numbers: [[Int]] = [[1, 2, 3], [4, 5], [6]]
let result: [Int] = numbers.flatMap { $0 }
print(result) // [1, 2, 3, 4, 5, 6]
let numbers: [[Int?]] = [[1, 2, 3], [nil], [4, 5], [6]]
let result: [Int?] = numbers.flatMap { $0 }
print(result) // [opt(1), opt(2), opt(3), nil, opt(4), opt(5), opt(6)]
filter
클로저로 전달된 함수를 적용해 결과가 참(True)인 요소로 같은 타입의 새로운 컬렉션 타입을 반환합니다.
let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result: [Int] = numbers.filter { $0 % 2 == 0 }
print(result) // [2, 4, 6, 8, 10]
reduce
클로저로 전달된 함수를 적용해 결합한 결과를 반환합니다.
- reduce는 2개의 전달인자를 가집니다. (초기값, 적용할 클로저)
- 순서대로 초기값에 클로저를 적용한 값을 결합해 다음 순서로 넘깁니다.(누적)
let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result: Int = numbers.reduce(0) { (num1: Int, num2: Int) -> Int in
return num1 + num2
}
let result: Int = numbers.reduce(0, +)
print(result) // 55
compactMap
클로저로 전달된 함수를 적용한 결과를 반환합니다. 이때 결과가 nil일 경우, 해당 결과는 무시됩니다.
let numbers: [[Int]?] = [[1, 2, 3], nil, [5, 6], nil, [7, 8]]
let result = numbers.compactMap { $0 }
print(result) // [[1, 2, 3], [5, 6], [7, 8]]
- 과거 compactMap의 자리에는 flatMap을 사용한 적이 있었기 때문에, 지금도 compactMap을 써야할 자리에 flatMap을 사용하면 deprecated되었다고 경고가 뜹니다.
참고자료
- https://jeonyeohun.tistory.com/265
- https://velog.io/@parkgyurim/Swift-Higer-order-function
- https://developer.apple.com/documentation/swift/sequence/map(_:)
- https://developer.apple.com/documentation/swift/sequence/flatmap(_:)-jo2y
- https://developer.apple.com/documentation/swift/string/filter(_:)
- https://developer.apple.com/documentation/swift/array/reduce(_:_:)
- https://developer.apple.com/documentation/swift/sequence/compactmap(_:)