map - 스탠다드 라이브러리 맵과 유사함.
let numbers = [5, 4, 3, 2, 1, 0]
let romanNumeralDict: [Int : String] =
[1:"I", 2:"II", 3:"III", 4:"IV", 5:"V"]
cancellable = numbers.publisher
.map { romanNumeralDict[$0] ?? "(unknown)" }
.sink { print("\\($0)", terminator: " ") }
//// Prints: "V IV III II I (unknown)"
tryMap - 에러를 방출하는 map
struct ParseError: Error{
}
func romanNumeral(from:Int) throws -> String{
let romanNumeralDict : [Int: String] = [1:"I", 2:"II", 3:"III", 4:"IV", 5:"V"]
guard let numeral = romanNumeralDict[from] else{
throw ParseError()
}
return numeral
}
let numbers = [1,2,3,0]
let cancellable = numbers.publisher
.tryMap{ try romanNumeral(from: $0)}
.retry(2)
.sink(
receiveCompletion: { print ("completion: \\($0)") },
receiveValue: { print ("\\($0)", terminator: " ") }
)
mapError : 에러를 다른에러로 치환함.
let numbers = [1,2,3,0]
let cancellable = numbers.publisher
.tryMap{ try romanNumeral(from: $0)}
.mapError{_ in NewError()}
.sink(
receiveCompletion: { print ("completion: \\($0)") },
receiveValue: { print ("\\($0)", terminator: " ") }
)
//I II III completion: failure(__lldb_expr_19.NewError())
replaceNil : nil을 다른 요소로 치환함.
let numbers: [Double?] = [1.0, 2.0, nil, 3.0]
numbers.publisher
.replaceNil(with: 0.0)
.sink { print("\\($0)", terminator: " ") }
//// Prints: "Optional(1.0) Optional(2.0) Optional(0.0) Optional(3.0)"
scan(_ initalResult: T, _ nextPratialRestult:)
기존 스위프트 라이브러리 reduce와 흡사해보임
let range = (0...5)
cancellable = range.publisher
.scan(0) { return $0 + $1 }
.sink { print ("\\($0)", terminator: " ") }
// Prints: "0 1 3 6 10 15 ".
tryScan : 에러를 방출할 수 있는 스켄임.
setFailureType(to:) :
let pub1 = [0, 1, 2, 3, 4, 5].publisher
let pub2 = CurrentValueSubject<Int, Error>(0)
let cancellable = pub1
.setFailureType(to: Error.self)
.combineLatest(pub2)
.sink(
receiveCompletion: { print ("completed: \\($0)") },
receiveValue: { print ("value: \\($0)")}
)
pub1의 Failure타입은 Never이고 pub2의 Failure타입은 Error이기 때문에 combineLatest시 Instance method 'combineLatest' requires the types 'Never' and 'any Error' be equivalent 컴파일 오류가 발생한다. setFailureType(to:)오퍼레이터를 이용해 Nerer → Error로 타입변환해주면 오류가 사라짐.