Last active
November 19, 2021 16:11
-
-
Save yimajo/6d2f8a8a3dfe908ac4b73f3ec0ed63c8 to your computer and use it in GitHub Desktop.
withCheckedThrowingContinuationとwithCheckedContinuationの違い
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private func addItem2() async throws { | |
// CheckedContinuation<Void, Error>)と型書かないといけないんだなあこれが | |
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in | |
writeContext.perform { | |
let newItem = Item(context: writeContext) | |
newItem.timestamp = Date() | |
do { | |
try writeContext.save() | |
continuation.resume() | |
} catch { | |
continuation.resume(throwing: error) | |
} | |
} | |
} | |
} | |
private func addItem3() async -> Result<Void, Error> { | |
await withCheckedContinuation { continuation in | |
writeContext.perform { | |
let newItem = Item(context: writeContext) | |
newItem.timestamp = Date() | |
do { | |
try writeContext.save() | |
continuation.resume(returning: .success(())) | |
} catch { | |
continuation.resume(returning: .failure(error)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
違いとか
結局呼び出し側でどうしたいか、に依存している。do catchしたいのかResultが欲しいのか。
その他
continuation.resume()
でVoidがTの場合専用のメソッドがある