4

This has bothered me for a little while. Is there a reason why I need to do this to set an object on a CKRecord.

task.record?.setObject(task.reference, forKey:ReferenceField)

instead of this

task.record?[ReferenceField] = task.reference 

From what I read in the docs CKRecord should be subscript friendly

Justin Milo
  • 575
  • 4
  • 15
  • It even says in the header file: In addition to objectForKey: and setObject:forKey:, dictionary-style subscripting (record[key] and record[key] = value) can be used to get and set values. – Justin Milo Nov 24 '14 at 15:51

1 Answers1

4

That subscripting is only available from Objective-C, since it's implemented using objectForKeyedSubscript: and setObject:forKeyedSubscript:. Happily, it's easy to extend CKRecord to allow Swift subscripting:

extension CKRecord {
    subscript(key: String) -> AnyObject! {
        get {
            return self.objectForKey(key)
        }
        set(newValue) {
            self.setObject(newValue as CKRecordValue, forKey: key)
        }
    }
}

NSHipster has a post on Objective-C subscripting if you want to know more. I'm surprised Swift doesn't bridge that automatically.

Nate Cook
  • 92,417
  • 32
  • 217
  • 178