为 restorationIdentifier 提供默认值

Provide default value for restorationIdentifier

我想覆盖 restorationIdentifier 变量,以便所有从 MyViewController 继承的视图控制器都将 restorationIdentifier 设置为其 class 名称。但是,似乎 Swift 不允许我这样做。

我要重载并提供默认实现的变量定义为:

var restorationIdentifier: String?

我尝试用以下方式覆盖它:

class MyViewController : UIViewController {

    override var restorationIdentifier: String? {
        return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
    }
}

编译器对我大喊:

Getter for restorationIdentifier with Objective-C selector restorationIdentifier conflicts with getter for restorationIdentifier from superclass UIViewController with the same Objective-C selector

我该如何克服这个问题?

您没有定义 setter,这使它成为只读的 属性。此代码对我有用:

override var restorationIdentifier: String? {
    get {
        return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
    }
    set(value) {
        super.restorationIdentifier = value
    }
}