compactMap는 parameter로 넘어온 클로저의 결과에서 nil이 아닌 값의 배열을 리턴한다.
let a: [Int?] = [nil, nil, 1]
let aa = a.compactMap { i in
return i
}
print(aa) // [1]
클로저는 물론 더욱 간단하게 작성할 수 있다.
let aa = a.compactMap { i in i }
let aa = a.compactMap { $0 }
반응형
'swift & iOS > swift' 카테고리의 다른 글
[swift] 빈 딕셔너리 dictionary 선언하기 (0) | 2022.02.07 |
---|---|
[swift] reduce (0) | 2022.02.04 |
[swift] 배열에 요소를 추가하는 append와 insert 그리고 딸기 케이크 (?) (0) | 2022.02.04 |
[swift] for ... in 에서 배열의 인덱스로 접근하기 (0) | 2022.02.04 |
[swift] 배열의 요소 여러 개를 한꺼번에 업데이트 하기 (0) | 2022.02.04 |