Home > Mobile >  How to write Hashable protocol yourself in swift
How to write Hashable protocol yourself in swift

Time:03-25

Is there a way to make custom protocols be propagative like standard Hashable, Equatable, Codable and so on i.e. when all properties of a struct/class conform to the protocol then the struct/class itself can conform to that protocol.

Say I have a simple protocol like this:

protocol State {
    init()
}

Suppose I have two structs:

struct State1: State {}
struct State2: State {}

They conform to the protocol, then I want to have another struct conforming to my protocol like this:

struct AppState: State {  // error: Type 'AppState' does not conform to protocol 'State'
    let state1: State1
    let state2: State2
}

In theory if all properties has an empty init() then it should be no problem implicitly implementing init in the AppState struct. But the compiler only understand an explicit init() in AppState. So is there a way to enhance my protocol State to have that feature?

CodePudding user response:

Unfortunately, no, this isn't meaningfully possible in Swift at the moment. Automatic conformance to protocols is currently limited to being implemented directly in the compiler (see, e.g., the implementation for Codable, and Equatable and Hashable); the only way you'd be able to hook into this mechanism would be to add direct support to the compiler — feasible if you're willing to fork the compiler and use that to compile all of your code, but that's a pretty big leap.

  • Related