3

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.

interrupt
  • 2,030
  • 17
  • 14

1 Answers1

6

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Found it few minutes before you posted your answer, but documentation was not explicit about no default implementation for struct. Thank you. – interrupt Jun 30 '20 at 14:03
  • 1
    @interrupt Yes it was: https://developer.apple.com/documentation/swift/identifiable/3285392-id "The stable identity of the entity associated with `self`. Available when Self conforms to AnyObject." – Alexander Jun 30 '20 at 14:06
  • how come your `MyIdentifiable` also fails for class then, if it also has a default for class? – qkhhly Jul 11 '21 at 04:04
  • @qkhhly that's not "my" `MyIdentifiable` and it also has no default implementation in the question. – Dávid Pásztor Jul 12 '21 at 08:32