Created
March 15, 2020 09:14
-
-
Save Koze/7fb045148c4772c5c28acb3958192cd9 to your computer and use it in GitHub Desktop.
Type-safe CKRecord extension by Objective-C keyPath.
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
// 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is more type-safe than below
https://gist.github.com/Koze/f6afb934377717bf34fd285439e86281