IOS application/Swift

25. [Swift] 고차함수 - map, flatMap, compactMap

개발자킹콩 2021. 8. 11. 20:25

map의 기능은 전체 아이템의 타입이나 상태, 형태, 값을 한번에 변경할 때 사용한다.

mapping 하는 함수이다. 결과를 배열의 상태로 반환한다.

 

 

 


 

 

map

 

Declaration

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

Example

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
names.map {
  $0 + "'s name"
}
<출력>
// ["Chris's name", "Alex's name", "Ewa's name", "Barry's name", "Daniella's name"]


let array = [1,2,3,4,5]
array.map {
    $0 + 1
}
<출력>
// [2, 3, 4, 5, 6]

 

 

 


 

 

 

swift 4.1 이상에서는 flatMap이 compactMap으로 변경되었지만,

현재는 두개를 구분해서 사용하고 있습니다.

 

공통점은 1차원 배열에 대해서는 같은 결과가 나온다. 

1. nil을 제거

2. optional binding 

let array1 = [1, nil, 3, nil, 5, 6, 7]
let flatMapTest1 = array1.flatMap{ $0 }
let compactMapTest1 = array1.compactMap { $0 }

print("flatMapTest1 :", flatMapTest1)
print("compactMapTest1 :", compactMapTest1)

<출력>
flatMapTest1 : [1, 3, 5, 6, 7]
compactMapTest1 : [1, 3, 5, 6, 7]

 

 

차이점은 이차원 배열 이상에서 나타난다.

let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]]
let flatMapTest2 = array2.flatMap { $0 }
let compactMapTest2 = array2.compactMap { $0 }

print("flatMapTest2 :",flatMapTest2)
print("compactMapTest2 :",compactMapTest2)

<출력>
// flatMapTest2 : [Optional(1), Optional(2), Optional(3), nil, Optional(5), Optional(6), nil, nil, nil]
// compactMapTest2 : [[Optional(1), Optional(2), Optional(3)], [nil, Optional(5)], [Optional(6), nil], [nil, nil]]

 

2차원 배열에 대해서는 flatMap과 compactMap 모두 nil을 제거하지 않는다.

중요한 것은 flatMap의 경우에는 flat하게 1차원 배열로 만들어 버린다. 그리고 optional을 씌운다.

compactMap의 경우는 배열의 상태를 유지하며, optional을 씌운다.

 

 

 

 


 

 

 

 

그렇다면 2차원 배열 이상에서 1차원 배열로 만들고, 1차원 배열로 만들고 싶으면 다음의 코드를 사용하면 된다.

 

let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]]
let flatMapTest2 = array2.flatMap { $0 }.compactMap{ $0 }

<출력>
// flatMapTest2 : [1, 2, 3, 5, 6]