我有一个简单的场景,我有一个父类,Person,它定义了一个名为“name”的属性,并包含一个“didSet”观察者…
class Person { var name: String? { didSet { println("Person name was set.") } } init() {} }
我还有一个名为Employee的Person子类,它为“name”属性添加了自己的“didSet”观察器,以便它可以监视该属性的更改…
class Employee: Person { override var name: String? { didSet { println("Employee name was set.") } } }
当我尝试运行代码时,我收到编译错误,但我无法弄清楚为什么或如何解决它。这是执行这些类的代码…
var person = Person() person.name = "Bob" var employee = Employee() employee.name = "Sally" // results in "Ambiguous use of 'name'" compile error
在我的情况下,我能够通过转换到基类来解决这个问题:
原文链接:https://www.f2er.com/swift/320701.html(employee as Person).name = "Sally"
这仍然似乎正确地分派到子类。例如:
class Person { var name: String { return "person" } } class Employee: Person { override var name: String { return "employee" } } let bob = Person() let alice = Employee() println((alice as Person).name) // prints "employee"