1

a common example:

protocol Foo {
    
}

extension Foo {
    static func abc() {
        // ...
    }
}

class Bar : Foo {
    
    static func abc() {
        // do something.

        (self as Foo.Type).abc() // it works well
    }
}

but if I add associatedtype (like SwiftUI.App) in protocol Foo, it report error:

protocol Foo {
    associatedtype Body = Scene
}

extension Foo {
    static func abc() {
        // ...
    }
}

class Bar : Foo {
    
    static func abc() {
        // do something.

        (self as Foo.Type).abc() // it reports error
    }
}

Protocol 'Foo' can only be used as a generic constraint because it has Self or associated type requirements

how to resolve it?

Jorris GM
  • 19
  • 2
  • 1
    Maybe check [this](https://www.hackingwithswift.com/example-code/language/how-to-fix-the-error-protocol-can-only-be-used-as-a-generic-constraint-because-it-has-self-or-associated-type-requirements) out – aheze Apr 06 '21 at 04:32
  • @aheze it seems not working. (self as Protocol.Type) can work well on normal protocols without associatedtype. but I don't known how to express it. – Jorris GM Apr 06 '21 at 04:39
  • How can you code what? What are you trying to do? You've already declared `@main` and adopted App. What else did you want to do? – matt Apr 06 '21 at 04:39
  • @matt I try to make a custom `static func main()`, and then call `SwiftUI.App.main()` again like `super.main()`. it's just an experiment, Not limited – Jorris GM Apr 06 '21 at 04:44
  • But there is no need to do that so why try? And what do you imagine `super` would mean? This is a struct, it has no inheritance. – matt Apr 06 '21 at 04:47
  • @matt I have updated code – Jorris GM Apr 06 '21 at 05:02
  • 1
    Ok, I see. But what you're trying to do is still very artificial. Protocol extension for injection of method implementation is not a form of dynamic dispatch inheritance. – matt Apr 06 '21 at 05:12
  • @matt It's just a little experiment. It looks like Foo::abc() in C++, I think we are able to call Foo.abc() in class Bar. Not dynamic dispatch but vtable – Jorris GM Apr 06 '21 at 05:23
  • @JorrisGM: As far as I see in your code, you are trying hard code a function to a protocol which is not planed for that! you are calling a function from protocol that has nothing inside other than just a name! – ios coder Apr 06 '21 at 11:45
  • Does this answer your question? [What does "Protocol ... can only be used as a generic constraint because it has Self or associated type requirements" mean?](https://stackoverflow.com/questions/24926310/what-does-protocol-can-only-be-used-as-a-generic-constraint-because-it-has) – AnderCover May 10 '21 at 16:54

0 Answers0