Recently I’ve been working with CloudKit in Swift. Many CloudKit methods take in a completion handler. Take a look at the following methods for CKDataBase object:

All of the completion handlers they take have two optional parameters, and the latter one is NSError?. I want similar logic in all of these completion handlers:

It causes a lot of code duplication if I rewrite the above logic over and over again in every single CloudKit method. So what I did is create a method takes a closure to handle the Do Some Other Stuff and output a completion handler with the above logic.

And, with this helper function, if I want to save a record to CloudKit and print the record ID when success, instead of writing:

I can simply write

Another example:

The above code perform a query on the database, get the distinct values of the attribute postID and print out the number of entities having distinct postID. The performQuery function has [CKRecord]? in its completion handler, and with the power of Swift generics type, our CKHandler function can still handle this situation.