Skip to content

Instantly share code, notes, and snippets.

@Koze
Last active March 15, 2020 09:13
Show Gist options
  • Save Koze/f6afb934377717bf34fd285439e86281 to your computer and use it in GitHub Desktop.
Save Koze/f6afb934377717bf34fd285439e86281 to your computer and use it in GitHub Desktop.
A little type-safe CKRecord extension to prevent typo.
extension CKRecord {
subscript<T: RawRepresentable>(key: T) -> CKRecordValueProtocol? where T.RawValue == CKRecord.FieldKey {
get {
return self[key.rawValue]
}
set {
self[key.rawValue] = newValue
}
}
}
enum Key: CKRecord.FieldKey {
case aaa
case bbb
}
func usage() {
let record = CKRecord(recordType: "Test")
record[Key.aaa] = true
let value = record[Key.aaa]
// type of `value` is `CKRecordValueProtocol?`
print(value)
// Optional(1)
}
@Koze
Copy link
Author

Koze commented Mar 15, 2020

Similar to CKRecord's default subscript access, getting a value requires a typecast.

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