Search code examples
swiftprotocols

Property alias (as arguably the most elegant solution for Identifiable)


What if I want to conform to a protocol and the protocol defines a property name which I don't like?
For example:

struct Currency: Identifiable {
    let id: String
    let rate: Double
}

But in this case it would be great to have a more meaningful name for "id" property. So I want to be able to do something like this:

struct Currency: Identifiable {
    propertyalias iso = id
    let iso: String
    let rate: Double
}

Solution

  • There's no such thing as a "property alias".

    However, you can wrap the property in a computed property that you can name as you see fit.

    struct Currency: Identifiable {
        let iso: String
        let rate: Double
    
        var id: String { 
            iso
        }
    }