Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

I've got a simple scenario in which I have a parent class, Person, which defines a property called "name" and includes a "didSet" observer...

class Person {

    var name: String? {
    didSet {
        println("Person name was set.")
    }
    }

    init() {}
}

I also have a subclass of Person called Employee which adds its own "didSet" observer for the "name" property so that it can monitor changes to that property...

class Employee: Person {

    override var name: String? {
    didSet {
        println("Employee name was set.")
    }
    }

}

When I try to exercise the code I get compile error but I can't figure out why or how to fix it. Here's the code that exercises these classes...

var person = Person()
person.name = "Bob"

var employee = Employee()
employee.name = "Sally"  // results in "Ambiguous use of 'name'" compile error
like image 755
Kris Schultz Avatar asked Jun 06 '14 16:06

Kris Schultz


3 Answers

I was able to work around this in my case by casting to the base class:

(employee as Person).name = "Sally"

This still appears to do the proper dispatch to the subclass. For instance:

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"
like image 53
Frank Schmitt Avatar answered Nov 09 '22 00:11

Frank Schmitt


As @sgaw points out, this has been confirmed as a known bug by the Apple engineers (for Xcode 6 Beta - Version 6.0 (6A215l))

https://devforums.apple.com/thread/229668?tstart=0

like image 13
Kris Schultz Avatar answered Nov 09 '22 01:11

Kris Schultz


I got this error because I had two properties declared with the same name.

On Objective-C the compiler used to give the error on the line the property was declared. Something like "duplicate property".

Now on Swift you get "Ambiguous use of..." on the line that you use to property... and you have to look everywhere to find the duplicate property.

like image 7
tomDev Avatar answered Nov 09 '22 01:11

tomDev