Last active
March 15, 2020 12:29
-
-
Save Koze/6c775db8ff5036385cf5ac42a5ca8754 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this is better than other ways for current Xcode 11.3.1 and Swift 5.1.
See also other trial and error.
https://gist.github.com/Koze/2ab02e4f249ce00242f2948f186a3fda
https://gist.github.com/Koze/7fb045148c4772c5c28acb3958192cd9
https://gist.github.com/Koze/f6afb934377717bf34fd285439e86281