Skip to content

Instantly share code, notes, and snippets.

@Koze
Last active March 15, 2020 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Koze/6c775db8ff5036385cf5ac42a5ca8754 to your computer and use it in GitHub Desktop.
Save Koze/6c775db8ff5036385cf5ac42a5ca8754 to your computer and use it in GitHub Desktop.
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
}
}
}
@objc protocol MyRecord {
var aaa: Bool { get set }
var bbb: String { get set }
}
protocol MyRecordProtocol {
subscript<Value: CKRecordValueProtocol>(keyPath keyPath: WritableKeyPath<MyRecord, Value>) -> Value? { get set }
}
extension CKRecord: MyRecordProtocol {
}
func usage() {
var record = CKRecord(recordType: "Test") as MyRecordProtocol
record[keyPath: \.aaa] = true
// Xcode doesn't show code completion, but shows error when use wrong keyPath and variable type.
let value = record[keyPath: \.aaa]
// Xcode infers type as `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