Why do we need a generic here? Isn't the protocol enough?

前端 未结 2 443
鱼传尺愫
鱼传尺愫 2021-01-16 13:16

I found the following example on the web about using generics together with protocols, however I don\'t understand why do we need generics at all, when all we need is to use

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-16 13:40

    Because this is using an inout (ugh) and not returning a value means that the generic is not required.

    When I would use a generic for this example is if the method signature was like this...

    func check(object: T) -> T {
    }
    

    This would then ensure that the type of object passed in and the type returned are the same type.

    Without the generic you could pass in an instance of...

    struct A: Healthy {}
    

    and return an instance of...

    struct B: Healthy {}
    

    Hmm... maybe this is still the case with the inout. Can you create another struct that conforms to the protocol and change the object to an instance of your new struct? Maybe... will have to check that later.

提交回复
热议问题