Search code examples
swiftidentifiable

Identifiable protocol in Swift: class vs struct


I'm using Swift 5.3

Trying to understand why when I declare this construction

final class MyActivity: Identifiable {
    public let iHaveNoId: String = ""
}

it compiles without any errors (even if I don't have "id" field implemented), while for struct

struct MyActivity: Identifiable {
    public let iHaveNoId: String = ""
}

I get an error (as expected) - Type 'MyActivity' does not conform to protocol 'Identifiable'

Moreover, if I copy Identifiable source code and rename it to my own name, e.g.

public protocol MyIdentifiable {
    associatedtype ID : Hashable
    var id: Self.ID { get }
}

then both struct and class implementing MyIdentifiable protocol will fail with a proper error Type 'MyActivity' does not conform to protocol 'MytIdentifiable'

I'm puzzled.


Solution

  • As the documentation of Identifiable states, it does provide a default implementation for id for class types. However, there is no default implementation for structs, hence you need to add the property manually.