3종 맵인 map, compactMap, flatMap입니다.
예제를 따라 하나씩 사용해 봅시다.
map
map: Returns an array containing the results of mapping the given closure over the sequence’s elements.(시퀀스의 요소에 대한 주어진 클로저를 매핑한 결과를 포함하는 배열을 반환합니다.)
func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
map은 클로저를 인자로 받아서 매핑한 결과를 배열로 반환해 줍니다.
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]
compactMap
compactMap: Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.(이 시퀀스의 각 요소로 주어진 변환을 호출하는 non-nil 결과를 포함하는 배열을 반환합니다.)
func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
compactMap은 매핑한 결과를 non-nil 배열로 반환해 줍니다.
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]
flatMap
flatMap: Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.(이 시퀀스의 각 요소와 함께 주어진 변환을 호출하는 연결된 결과를 포함하는 배열을 반환합니다.)
func flatMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
flatMap은 매핑한 결과를 연결된 배열로 반환해 줍니다.
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,
1차원 배열을 반환받길 원한다면 flatMap,
위 두 사례가 아니라면 map을 사용하면 될 것 같네요.
'Swift' 카테고리의 다른 글
Vision: visionOS simulator (0) | 2023.08.22 |
---|---|
Vision: visionOS란? (0) | 2023.08.22 |
SwiftUI: Mask Design (0) | 2023.08.11 |
SwiftUI: BlendMode (0) | 2023.08.09 |
SwiftUI: 온보딩 (0) | 2023.08.07 |