Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot pass function of type '(String) async -> ()' to parameter expecting synchronous function type

I have created simple async function to fetch all records from cloudkit for a given types:

func fetchAllOf(
    types: [String],
    handler: ProgressHandler?,
    completion: ErrorHandler?
) async {
    var newTypes = types
    var allRecords = [CKRecord]()
    newTypes.forEach { type in
        await fetchAllOf(type: type, handler: handler) { records, error in
            guard let error = error else {
                allRecords += records
                return
            }
            completion?(error)
        }
    }
}

where:

private func fetchAllOf(
    type: String,
    predicate: NSPredicate = NSPredicate(value: true),
    handler: ProgressHandler?,
    completion: RecordsErrorHandler?
) async {
}

Why do I have an error there?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

Don’t mix (custom) completion handlers with async/await.

The error occurs because a regular forEach closure is not async and doesn’t have a return value.

Make fetchAllOf(type:handler:) – the singular one – also async (and throws) and write something like

func fetchAllOf(
    types: [String],
    handler: ProgressHandler?) async throws -> [CKRecord] {
        var allRecords = [CKRecord]()
        for aType in types {
            let records = try await fetchAllOf(type: aType, handler: handler)
            allRecords += records
        }
        return allRecords
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading