Yesterday I realized my database had duplicate records, and that CloudKit doesn’t support unique constraints. So I added a check to make sure a record doesn’t exist before writing it in. My code evolved into a mix of bits from the documentation and a few phone-a-friends with ChatGPT. It worked. But how?
Today I learned the fetch
method on CKDatabase
takes in a completion handler as a parameter, which gets called after the operation with the outcome of the fetch. The completion handler itself takes in a single Result
parameter, which is a basic type from the Swift Standard Library.
@frozen public enum Result<Success, Failure> where Failure : Error {
case success(Success)
case failure(Failure)
}
Notice the <Success, Failure>
in the enum’s declaration. It’s using Swift Generics as a placeholder to represent any Success or Failure value. In CloudKit, these are defined by the fetch
method to return either a tuple of results, or an error if the request fails. So in the case of .success
, I get back an array of matchResults
. If this array .isEmpty
, a write won’t create a duplicate record.
CloudKit
Sunday July 23, 2023