XCode 16.4 日本語化計画
エラーを同期的に返すことができない場合は、API の一部として結果を提供します。
失敗する可能性のある関数、メソッド、またはその他の API を記述する場合、宣言で throws キーワードを使用して、API 呼び出しがエラーを throw する可能性があることを示します。ただし、非同期で返される API モデル化するために throws キーワードを使用することはできません。代わりに、Result 列挙型を使用して非同期呼び出しが成功したか失敗したかに関する情報を取得し、Result.success(_:) および Result.failure(_:) ケースに関連した値を使用して、呼び出しの結果に関する情報を保持します。
以下の例は、非同期の乱数ソースをモデル化しています。fetchRemoteRandomNumber(completion:) メソッドは同期的に Void を返し、ランダムな結果または失敗に関する情報を含む Result<Int, EntropyError> インスタンスを使用して非同期的に完了ハンドラを呼び出します。
let queue = DispatchQueue(label: "com.example.queue") enum EntropyError: Error { case entropyDepleted } struct AsyncRandomGenerator { static let entropyLimit = 5 var count = 0 mutating func fetchRemoteRandomNumber( completion: @escaping (Result<Int, EntropyError>) -> Void ) { let result: Result<Int, EntropyError> if count < AsyncRandomGenerator.entropyLimit { // Produce numbers until reaching the entropy limit. result = .success(Int.random(in: 1...100)) } else { // Supply a failure reason when the caller hits the limit. result = .failure(.entropyDepleted) } count += 1 // Delay to simulate an asynchronous source of entropy. queue.asyncAfter(deadline: .now() + 2) { completion(result) } } }
リモート乱数ジェネレータのユーザーは、成功と失敗の両方のケースをどのように処理するかを決定できます。
var generator = AsyncRandomGenerator() // Request one more number than the limit to trigger a failure. (0..<AsyncRandomGenerator.entropyLimit + 1).forEach { _ in generator.fetchRemoteRandomNumber { result in switch result { case .success(let number): print(number) case .failure(let error): print("Source of randomness failed: \(error)") } } } print("Waiting on some numbers.") dispatchMain() /* Prints: success(29) success(46) success(85) success(39) success(84) Source of randomness failed: entropyDepleted */
成功。Success の値を保存します。
失敗。Failure の値を保存します。