Last active
March 15, 2020 09:13
-
-
Save Koze/f6afb934377717bf34fd285439e86281 to your computer and use it in GitHub Desktop.
A little type-safe CKRecord extension to prevent typo.
This file contains hidden or 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 { | |
subscript<T: RawRepresentable>(key: T) -> CKRecordValueProtocol? where T.RawValue == CKRecord.FieldKey { | |
get { | |
return self[key.rawValue] | |
} | |
set { | |
self[key.rawValue] = newValue | |
} | |
} | |
} |
This file contains hidden or 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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Similar to CKRecord's default subscript access, getting a value requires a typecast.