map compactmap flatmap操作符的区别
之前已经使用过了map
操作符:
[1, 2, 3]
.publisher
.map { int in "Number: \(int)" }
.sink(receiveValue: { int in
print(int)
})
输出:
Number: 1
Number: 2
Number: 3
compactmap可用于过滤nil
[1, 2, nil, 3, nil, 4, nil, 5].publisher
.compactMap { $0 }
.sink(receiveValue: { int in
print("Received \(int)")
})
输出:
Received 1
Received 2
Received 3
Received 4
Received 5
flatmap可用于将数组降维,例如 [[1, 2], [3, 4]] -> [1, 2, 3, 4]
[1, 2, 3].publisher.flatMap({ int in
return (0..<int).publisher
}).sink(receiveCompletion: { _ in }, receiveValue: { value in
print("value: \(value)")
})
输出
value: 0
value: 0
value: 1
value: 0
value: 1
value: 2