struct Result.Publisher
Discussion 解説
In the following example, good
provides a successful result with the integer value 1
. A sink subscriber connected to the result’s publisher receives the output 1
, followed by a normal completion (Subscribers
).
以下の例において、good
は成功結果を整数値の1
で提供します。結果のもつパブリッシャーに接続した流し先の加入者は出力1
、それに続けてある正常完了(Subscribers
)を受け取ります。
let goodResult: Result<Int, MyError> = .success(1)
goodResult.publisher
.sink(receiveCompletion: { print("goodResult done: \($0)")},
receiveValue: { print("goodResult value: \($0)")} )
// Prints:
// goodResult value: 1
// goodResult done: finished
In contrast with the Just
publisher, which always publishes a single value, this publisher might not send any values and instead terminate with an error, if the result is Result
. In the next example, bad
is a failure result that wraps a custom error. A sink subscriber connected to this result’s publisher immediately receives a termination (Subscribers
).
常に単一の値を出版するJust
パブリッシャーと対照的に、このパブリッシャーは全く値を送信しないで代わりにエラーで終了するかもしれません、もし結果がResult
であるならば。次の例において、bad
はある不成功結果です、それはあるあつらえのエラーをラップするものです。結果のもつパブリッシャーに接続した流し先の加入者は、直ぐにある終了(Subscribers
)を受け取ります。
struct MyError: Error, CustomDebugStringConvertible {
var debugDescription: String = "MyError"
}
let badResult: Result<Int, MyError> = .failure(MyError())
badResult.publisher
.sink(receiveCompletion: { print("badResult done: \($0)")},
receiveValue: { print("badResult value: \($0)")} )
// Prints:
// badResult done: failure(MyError)