Why can't I use subscripting on a CKRecord object in swift?

若如初见. 提交于 2019-12-01 05:06:26

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/27108714/why-cant-i-use-subscripting-on-a-ckrecord-object-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!