如何在Swift中覆盖Objective-C的只读属性?

时间:2015-08-06 12:20:43

标签: objective-c swift

这是在objective-c中定义的方式:

@interface AFHTTPRequestOperation : AFURLConnectionOperation

@property (readonly, nonatomic, strong) id responseObject;

如何将sth分配给此属性?

我想嘲笑这个属性供以后使用。所以我需要在Swift中拥有自己的responseObject覆盖。任何想法如何做到这一点?我可以继承,扩展或其他任何东西。唯一的问题是它必须是AFHTTPRequestOperation的类型。

class MyRequestOperation: AFHTTPRequestOperation {

    override var responseObject: [String: AnyObject]
}

产生错误:

  

Getter for responseObject with Objective-C selector responseObject conflicts with getter for responseObject from superclass AHTTPRequestOperation with the same Objective-C selector

2 个答案:

答案 0 :(得分:16)

所以,答案很简单,因为@Atul Mishra说:

class MyRequestOperation: AFHTTPRequestOperation {

    var myOverridenResponseObject: AnyObject?

    override var responseObject: AnyObject? {

        get {
            return myOverridenResponseObject
        }

        set {
            myOverridenResponseObject = newValue
        }
    }
}

答案 1 :(得分:7)

通过在子类属性override中提供getter和setter,可以将继承的只读属性作为读写属性提供。但是,您不能将继承的读写属性作为只读属性提供。 为了更好地澄清,请参考https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html#//apple_ref/doc/uid/TP40014097-CH17-XID_300