본문 바로가기

swift 기본 문법

Swift 고차함수) flatMap, compactMap 알아보기

반응형

CompactMap

func compactMap<ElementOfResult>(_ transform: (Int?) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

해당 시퀀스의 각 요소로 지정된 변환을 호출한 nil이 아닌 결과를 포함하는 배열을 반환한다. 라는 의미를 가지고 있다.

 

변환하는 과정에서 옵셔널 값이 생성되는 경우 해당 메서드를 통해 옵셔널이 아닌 값들을 받을 수 있다.

compactMap이 옵셔널 바인딩의 기능을 가지고 있기 때문에 가능하다.

let array = ["1", "일", "2", "이"]

let map = array.map { item in
    return Int(item)
}
print(map)

let compactMap = array.compactMap { item in
    return Int(item)
}
print(compactMap)
//[Optional(1), nil, Optional(2), nil]
//[1, 2]

flatMap

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

시퀀스의 각 요소로 주어진 변환을 호출한 연결 결과가 포한된 배열을 반환한다.

 

간단하게 말하면 2차원 배열을 1차원 배열로 만들고자할 때 사용한다. 

func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
let secondArray = [
    ["일"],
    ["이, 삼"],
    ["사", "오"]
]

let flatMap = secondArray.flatMap { (item: [String]) in
    return item
}
let flatMap2 = secondArray.flatMap { $0 }
print(flatMap)
//["일", "이, 삼", "사", "오"]

 

2차원 배열 안에서 nil이 존재한다면 compactMap을 같이 사용해 준다. 

let secondArray = [
    ["일"],
    ["이, 삼"],
    ["사", "오"],
    [nil, "육"]
]
let mapArray = secondArray.flatMap { $0 }.compactMap { $0 }
print(mapArray)
//["일", "이, 삼", "사", "오", "육"]
반응형