iTranslated by AI
[Swift Concurrency] Bridging the Delegate Pattern to async Functions
Summary
- Attempting to bridge something that uses the Delegate pattern to an async function.
- Use
withCheckedContinuation(function:_:)within an async function and hold the passedCheckedContinuationin a class or similar. - After the process is finished, return a value to the async function using
CheckedContinuation.resume(), etc.
For Closure Patterns (e.g., completionHandler), see here
Converting Delegate Patterns into async Functions
Concurrency, introduced in Swift 5.5 and later—when attempting to use it in existing projects—will likely coexist for some time with traditional callbacks such as completionHandler or event-driven systems using the Delegate pattern.
Let's look at an example of how to turn this into a single async function.
Prepare an async Function
First, let's prepare an async function.
import Foundation
class ViewModel: NSObject {
// Read e-money card balance using Core NFC
func readBalance() async throws -> Int {
// ...
}
}
Calling withCheckedContinuation(function:_:) or similar
Inside this readBalance(), call either withCheckedContinuation(function:_:) or withCheckedThrowingContinuation(function:_:) and return it. The difference between the two is whether they throw an error or not. Since these are async functions, the await keyword is required.
import Foundation
class ViewModel: NSObject {
func readBalance() async throws -> Int {
return try await withCheckedThrowingContinuation { continuation in
// ...
}
}
}
Holding CheckedContinuation within the class
Place the CheckedContinuation obtained from the closure of withCheckedContinuation(function:_:) or withCheckedThrowingContinuation(function:_:) into a property prepared in the class.
In this case, it is named activeContinuation, with the Int return type of readBalance() and Error for throwing passed as generics.
Next, write the code that triggers the event, just as you would have done before the introduction of Concurrency.
import Foundation
class ViewModel: NSObject {
private var activeContinuation: CheckedContinuation<Int, Error>?
private var session: NFCTagReaderSession?
func readBalance() async throws -> Int {
return try await withCheckedThrowingContinuation { continuation in
activeContinuation = continuation
// Following code is the same as before introducing Concurrency
session = NFCTagReaderSession(pollingOption: .iso18092, delegate: self)
session?.begin() // Trigger event
}
}
}
Call CheckedContinuation.resume() and Others Once the Process is Finished
Once you have prepared the value to be returned or are ready to return an error, return them using CheckedContinuation.resume(returning:), CheckedContinuation.resume(throwing:), or CheckedContinuation.resume(with:), etc.
As stated in the documentation, this resume method must be called exactly once on every possible execution path in the program.
Calling the resume method two or more times results in undefined behavior, and conversely, if it is never called, the async function being created will remain in a state where it never resumes. The CheckedContinuation used in this article is designed to perform runtime checks for whether resume has been called or forgotten. While UnsafeContinuation, which does not perform these runtime checks, is also available, its use should be limited to situations where performance is highly critical, and it must be verified with thorough testing.
In the code below, activeContinuation is properly disposed of by setting it to nil after calling resume, so that there are no issues even if resume is mistakenly attempted to be called twice or more.
import CoreNFC
extension Hoge: NFCTagReaderSessionDelegate {
func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
// Not used this time
}
func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
// This method is called when an error occurs
activeContinuation?.resume(throwing: error)
activeContinuation = nil
}
func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
// This method is called if successful (in this case, if an e-money card is detected)
// Implementation of e-money card reading is omitted
// Assuming the balance is stored in `balance` as an `Int`
activeContinuation?.resume(returning: balance)
activeContinuation = nil
}
}
Try calling the completed async function
Now that the async function is complete, let's try calling it. Since the readBalance() we created is async and throws, the caller will need the try await keywords.
If you want to call it from a place where Concurrency is not supported, wrap it in Task.init(priority:operation:).
Task {
do {
let balance = try await viewModel.readBalance()
print("Balance:", balance)
} catch {
print(error.localizedDescription)
}
}
Don't forget to call resume and dispose of the held CheckedContinuation
With traditional callbacks using completionHandler or the Delegate pattern, for instance, if you successfully obtained a value but forgot to return it to the original process, it wouldn't result in a compiler error, often leading to hard-to-notice omissions in processing.
However, these Swift Concurrency mechanisms are helping to reduce that concern. While many of the frameworks provided by Apple have already been made compatible with async through the Interoperability with Objective-C mechanism, we've seen that for patterns using other closures or the Delegate pattern, you can manually make them async using mechanisms like CheckedContinuation.
In the case of this manual implementation, be sure not to forget to call resume and dispose of the held CheckedContinuation.
[Bonus] Making it available only in Xcode 13.2 or later
The readBalance() we created this time will attempt to build even in Xcode 13.0 and Xcode 13.1 as it is, resulting in an error like "withCheckedThrowingContinuation(function:_:) or Concurrency is only available in iOS 15.0 or newer!"
Therefore, by taking advantage of the fact that the Swift compiler in Xcode 13.2 is version 5.5.2, you can write the code as follows so that it can only be built in Xcode 13.2 or later.
import Foundation
#if compiler(>=5.5.2) && canImport(_Concurrency)
class ViewModel: NSObject {
private var activeContinuation: CheckedContinuation<Int, Error>?
private var session: NFCTagReaderSession?
func readBalance() async throws -> Int {
return try await withCheckedThrowingContinuation { continuation in
activeContinuation = continuation
// Following code is the same as before introducing Concurrency
session = NFCTagReaderSession(pollingOption: .iso18092, delegate: self)
session?.begin() // Trigger event
}
}
}
#endif
Sample Code
References
Discussion