Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] map과 flatMap 차이 (CollectionType, Optional) 본문

iOS 응용 (swift)

[iOS - swift] map과 flatMap 차이 (CollectionType, Optional)

jake-kim 2024. 4. 1. 01:31

1. map과 flatMap의 차이 - CollectionType에서 쓰임

  • CollectionType에서 접근: array와 같은 각 개별 요소에 접근하여 변화를 주는 것
    • 만약 Element중에 Optional값이 있다면 flatMap은 unwrap을 해주고, map은 unwrap을 해주지 않음
    • 단, flatMap은 deprecated되어 compactMap 사용
// 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
let c = [1, 2, Optional(3)]
    .flatMap { $0 }
print(c) // [1, 2, 3]

2. map과 flatMap의 차이 - Optional에서 쓰임

  • map과 flatMap모두 클로저 안에서 unwrap된 값을 받음
    • (단 리턴 값은 Optional임)
Optional(3)
    .map { print($0) } // 3

Optional(3)
    .flatMap { print($0) } // 3
  • 타입 캐스팅을 할 때, flatMap은 unwrap해서 반환해주고, map은 그대로 반환
let aa = Optional(3)
    .map { ($0 + 1) as? String }
print(aa) // Optional(nil)

let bb = Optional(3)
    .flatMap { ($0 + 1) as? String }
print(bb) // nil
  • flatMap사용하여 safeAreaInset 구하는 코드에서도 타입 캐스팅 하는 부분에서 flatMap을 사용하면 unwrap된 값을 반환해주어 3번째 map 연산자에서 map(\.?.)이런 형식으로 접근 안해도됨
    • safeAreaInsets 구하는 관련 자세한 내용은 이전 포스팅 글 참고
let a = UIApplication.shared.connectedScenes.first
    .flatMap { $0 as? UIWindowScene }
    .map(\.windows.first?.safeAreaInsets.bottom) ?? 0

let b = UIApplication.shared.connectedScenes.first
    .map { $0 as? UIWindowScene }
    .map(\.?.windows.first?.safeAreaInsets.bottom) ?? 0

 

cf) dictionary에서 value값들만 쭉 바꾸고 싶은 경우? 

Comments