swift & iOS/swift

[swift] 배열에서 nil 이 아닌 값만 추려내기 (compactMap)

whale3 2022. 2. 4. 16:51

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 }

 

반응형