[iOS | Swift] map, flatMap., compactMap 비교하기

someng·2023년 5월 25일
0

iOS

목록 보기
32/33

🍄 map

: 배열 내부의 값을 하나씩 mapping

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]

🍄 flatMap & compactMap

Swift 4.1부터 기존의 flatMapcompactMap으로 바뀐다. (flatMap 남아있음)

📌 기존의 flatMap 역할
1. flatten
2. nil을 제거
3. 옵셔널 바인딩

🌴 1차원 배열 (flatMap, comPactMap 동일)

  1. nil 을 제거
  2. 옵셔널 바인딩
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]

🌴 2차원 배열

  • nil 제거 X
  • flatMap 만 2차원 배열에서 1차원 배열로 flatten
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]]


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]
profile
👩🏻‍💻 iOS Developer

0개의 댓글