-
Swift - compactmapdeveloping study 2024. 1. 8. 20:24
var array = [1,nil, 3, 9, nil, 6] var mapTest = array.map { $0 } var compactMapTest = array.compactMap { $0 }
swift의 고차함수중 filter와 reduce는 나름대로 많이 사용하는 반면 왜인지 모르겠지만 map은 거리가 먼 느낌.
근데 map도 filter나 reduce처럼 배열 내부 요소들을 클로저 안에서 내가 작성한대로 만들어서 return해주는? 거라고 대략 이해는 하고 있다. 근데 또 compactmap은 무엇인지..
(flatmap도 있는데 이건 deprecatede됨.)
compactmap은 map과의 차이점은 non-nil이라는게 키워드인 것 같다.
compactMap(_:)
Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.애플 문서의 설명.
직접 테스트해보니 이해가 바로 됐다.
var array = [1,nil, 3, 9, nil, 6] var mapTest = array.map { $0 } var compactMapTest = array.compactMap { $0 } //로그 //mapTest: [Optional(1), nil, Optional(3), Optional(9), nil, Optional(6)] //compactMapTest: [1, 3, 9, 6]
map을 사용한 배열 결과는 nil과 Optional가지 붙어서 리턴이 됐다.
하지만 compactMap은 non-nil결과를 리턴한다는 문서 설명처럼 Optional역시 없으며 nil인 값은 아예 제거된 체로 리턴된 것 확인.
'developing study' 카테고리의 다른 글
Swift- enumerated() (1) 2024.01.11 Swift - components이용해 문자열 쪼개기 (0) 2024.01.11 Swift - reduce (0) 2024.01.04 SwiftUI - trim() (0) 2023.04.16 Tuist 설치시 오류 - dylib not found (0) 2023.04.11