为什么不能快速对CKRecord对象使用下标? [英] Why can't I use subscripting on a CKRecord object in swift?
问题描述
这困扰了我一段时间。我有理由为什么要在CKRecord上设置对象。
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)
代替此
task.record?[ReferenceField] = task.reference
从我在CKRecord文档中看到的内容来看,下标应该是友好的
From what I read in the docs CKRecord should be subscript friendly
推荐答案
该下标仅可从Objective-C获得,因为它是使用 objectForKeyedSubscript:
和 setObject:forKeyedSubscript:
实现的。幸运的是,扩展 CKRecord
以允许Swift下标很容易:
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具有有关Objective-C下标的帖子,如果您想了解更多。我很惊讶Swift无法自动桥接。
NSHipster has a post on Objective-C subscripting if you want to know more. I'm surprised Swift doesn't bridge that automatically.
这篇关于为什么不能快速对CKRecord对象使用下标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!