Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61880

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?

enter image description here

Upvotes: 2

Views: 2471

Answers (1)

vadian
vadian

Reputation: 285290

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
}

Upvotes: 5

Related Questions