Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I get the error 'Type does not conform to protocol' when using a struct that conforms to the protocol?

I’ve got a protocol called DTO.

public protocol DTO {
    static func GetDefaultInstance() -> DTO
}

I’ve got a struct that conforms to DTO called Exercise.

public struct Exercise: Codable, Identifiable, DTO {
    public var id: String { return ExerciseId }
    public var ExerciseId: String
    public var ExerciseName: String
    
    public static func GetDefaultInstance() -> Exercise { //error here
        return Exercise(ExerciseId: "", ExerciseName: "")
    }
}

Since Exercise conforms to DTO why can’t I return Exercise? It is a DTO.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that the signature in the protocol and the declaration don’t actually match, because while Exercise conforms to DTO, it is not exactly DTO.

If you change the protocol definition to return Self, then the protocol will expect that the function returns the type that is implementing the protocol, and that method signature you have will work.

public protocol DTO {
    static func GetDefaultInstance() -> Self
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading