What is CompactMap operator in Swift Combine?
import UIKit
import Combine
var cancellable: AnyCancellable!
let dictionary: [Int : String] = [1: "One", 2: "Two", 3: "Three", 5: "Five"]
let numbers = (0...5)
cancellable = numbers.publisher
.sink { numberKey in
print(dictionary[numberKey])
}
The result of above code :
nil
Optional("One")
Optional("Two")
Optional("Three")
nil
Optional("Five")
I want to unwrap value and this is the time to use CompactMap operator.
Let's add CompactMap operator to above code
import UIKit
import Combine
var cancellable: AnyCancellable!
let dictionary: [Int : String] = [1: "One", 2: "Two", 3: "Three", 5: "Five"]
let numbers = (0...5)
cancellable = numbers.publisher
.compactMap({ numberKey -> String? in
return dictionary[numberKey]
})
.sink { value in
print(value)
}
The result of above code :
One
Two
Three
Five
댓글 없음:
댓글 쓰기