在Swift中重写子类中的属性的正确方法是什么?

时间:2014-09-26 11:33:17

标签: ios inheritance properties swift override

我也偶然发现了这个问题,然而,没有明确的答案

  

"Ambiguous use of 'propertyName'" error given overridden property with didSet observer

问题:我想覆盖子类中的属性。

让我用一个例子说明问题:

我有一个名为A的类及其子类B

A类

class A {

    var someStoredProperty : Int? 

}

B类

class B : A{

    override var someStoredProperty : Int?{

        willSet{

            //add to superclass's setter 
            someStoredProperty = newValue! + 10
        }

    }

}

我尝试设置B

的继承属性
var b = B()
b.someStoredValue = 10 // Ambiguous use of someStoredProperty

编译器告诉我

Ambiguous use of someStoredProperty

为什么?

更新

class TableViewRow{

    typealias ClickAction = (tableView:UITableView, indexPath:NSIndexPath) -> Void
    var clickAction : ClickAction?
}

class SwitchTableViewRow: TableViewRow {

    override var clickAction : ClickAction? {

        didSet{

            //override setter
        }

    }

}

用法:

var switchRow = SwitchTableViewRow()
switchRow.clickAction = {    
       //^
       //|
       //|
 //ambiguous use of clickAction
[unowned self, unowned switchRow] (tableView: UITableView, indexPath: NSIndexPath) in

    //do something

}

1 个答案:

答案 0 :(得分:12)

我在6.1中没有得到错误,但潜在的问题是你在这里有一个无限循环。你的意思是:

// This is wrong, but what you meant
override var someStoredProperty: Int? {
    willSet {
        super.someStoredProperty = newValue! + 10
    }
}

请注意super。 (这是我强烈建议在属性上使用self.的另一个原因,以便在存在这些无限循环时明确这一点。)

但这段代码毫无意义。在设置器之前,您将值设置为x + 10。然后,将值设置为x。你真正的意思是:

override var someStoredProperty: Int? {
    didSet {
        if let value = someStoredProperty {
            super.someStoredProperty = value + 10
        }
    }
}