Search code examples
swiftidentifiable

Why does computed "id" create this alleged ambiguity?


I have a pet peeve against the misuse of "id" to mean "ID." Unfortunately, the Identifiable protocol requires a hard-coded member called id for conformance; fortunately you can use a computed property for it. But doing so creates a perplexing complaint from the compiler:

struct BMessage: Codable, Identifiable
{
    var id: String  // Misspelling of "ID" required for Identifiable protocol
    {
        get
        {
            return ID // "Ambiguous use of ID"
        }
    }

    var ID: String = ""

...

    init()
    {
        ID = UUID().uuidString // "Ambiguous use of ID"
    }
...
}

To get around this, I have to put self.ID all over the place. Why?


Solution

  • The Identifier protocol declares an associated type named ID. Your struct's ID property name is causing a conflict and resulting in the ambiguous name error.

    Property names should start with lowercase letters so simply using id instead of trying to use ID makes more sense any way. If you were trying to name the property as ID due to JSON parsing, you can use CodingKeys to map the ID JSON key to the id struct property.