Use Type Erasure return Generic Type in a function with Swift (Cannot convert return expression of type…)

前端 未结 3 731
一生所求
一生所求 2021-01-25 01:31

I have a problem with generics in swift. Let\'s expose my code.


protocol FooProtocol {
    associatedtype T
}

protocol Fooable { }
extension Int : Fooable { }
         


        
3条回答
  •  难免孤独
    2021-01-25 02:04

    EDIT to respond to the edit to the question:

    createTwo doesn't work because you have the same misconception as I said in my original answer. createTwo decided on its own that F should be either String or Int, rather than "any type that conforms to Fooable".

    For createOne, you have another common misconception. Generic classes are invariant. AnyFoo is not a kind of AnyFoo. In fact, they are totally unrelated types! See here for more details.

    Basically, what you are trying to do violates type safety, and you redesign your APIs and pick another different approach.


    Original answer (for initial revision of question)

    You seem to be having a common misconception of generics. Generic parameters are decided by the caller, not the callee.

    In createOne, you are returning anyFoo, which is of type AnyFoo, not AnyFoo

    . The method (callee) have decided, on its own, that P should be Int. This shouldn't happen, because the caller decides what generic parameters should be. If the callee is generic, it must be able to work with any type (within constraints). Anyway, P can't be Int here anyway, since P: FooProtocol.

    Your createOne method should not be generic at all, as it only works with Int:

    func createOne() -> AnyFoo {
        let anyFoo = AnyFoo(p: FooImpClass())
        return anyFoo
    }
    

提交回复
热议问题