Home > Software engineering >  What is the syntax for this closure for fetchDatabaseChangesResultBlock?
What is the syntax for this closure for fetchDatabaseChangesResultBlock?

Time:02-20

iOS Cloudkit FetchDatabaseChangesOperation() has a closure block defined as:

fetchDatabaseChangesResultBlock: ((_ operationResult:
    Result<(serverChangeToken: CKServerChangeToken, moreComing: Bool), Error>) -> Void)?

My question is, what does an actual closure block look like?

For example, I tried this, which compiles:

let operation = CKFetchDatabaseChangesOperation(previousServerChangeToken: changeToken)

operation.fetchDatabaseChangesResultBlock = {
    result in
}

In need to get the serverChangeToken, the moreComing value, and the Error. But I can't figure out what "result" is, or even if I have the right signature.

Any help would be appreciated! I can't figure this one out.

Followup: based on the answer, here is the concrete code that solved the problem.

operation.fetchDatabaseChangesResultBlock = {
            result in
            
            switch result {
            case .success(let tuple):
                let token = tuple.serverChangeToken
                let moreComing = tuple.moreComing
                  // Do something
                }
            case .failure(let error):
                // Handle error
                break;
            }
        }

CodePudding user response:

As you saw, closure's type is (Result<(serverChangeToken: CKServerChangeToken, moreComing: Bool), Error>) -> Void)?. Breaking that down we see:

  1. The whole thing is optional, meaning it can be nil.
  2. When it's not nil, it's a closure of type (Result<(serverChangeToken: CKServerChangeToken, moreComing: Bool), Error>) -> Void.
  3. This closure type has one parameter, and doesn't return anything.
  4. The parameter has type Result<(serverChangeToken: CKServerChangeToken, moreComing: Bool), Error>. This is the Result type from the Swift standard library, whose:
    • Success type is (serverChangeToken: CKServerChangeToken, moreComing: Bool) (just a tuple of two values)
    • Failure type is just Error (i.e. it's not constrained anymore than the Failure: Error constraint that Result already has in place).
  • Related