Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifiable protocol in Swift: class vs struct [duplicate]

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.

like image 675
interrupt Avatar asked May 02 '26 12:05

interrupt


1 Answers

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.

like image 104
Dávid Pásztor Avatar answered May 05 '26 08:05

Dávid Pásztor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!