Skip to content

Instantly share code, notes, and snippets.

@Koze
Created March 15, 2020 09:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Koze/7fb045148c4772c5c28acb3958192cd9 to your computer and use it in GitHub Desktop.
Type-safe CKRecord extension by Objective-C keyPath.
extension CKRecord {
public subscript<Root, Value: CKRecordValueProtocol>(keyPath keyPath: WritableKeyPath<Root, Value>) -> Value? {
get {
let key = NSExpression(forKeyPath: keyPath).keyPath
return self[key]
}
set {
let key = NSExpression(forKeyPath: keyPath).keyPath
self[key] = newValue
}
}
}
// need `@objc` to extract keyPath string with NSExpression
@objc protocol MyRecord {
var aaa: Bool { get set }
var bbb: String { get set }
}
func usage() {
let record = CKRecord(recordType: "Test")
record[keyPath: \MyRecord.aaa] = true
let value = record[keyPath: \MyRecord.aaa]
// type of `value` is `Bool?`
print(value)
// Optional(true)
}
@Koze
Copy link
Author

Koze commented Mar 15, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment