BlackHatSamurai BlackHatSamurai - 5 months ago 28
Swift Question

Overloading Method in Swift Gives Objective C error

I'm trying to extend the

CKRecord
class to allow subscripting. To do so, I've created a new file, called
CKRecordHelper
, and done:

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


However, I'm getting an error on the
get
and
set
lines, which reads:


Subscript getting with Objective-C selector 'objectoForKeyedSubscript:' conflicts with method 'objectForKeyedSubscript' with the same Objective-C selector.


How do I fix this? From what I understand, Objective-C doesn't allow method overloading, but I'm using Swift. Ultimately, I'm just looking to allow a
CKRecord
to allow subscripting on it.

Answer

Use @nonobjc attribute to hide the method from ObjC runtime so Swift compiler doesn't need to worry about compatibility with ObjC code.

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