3

I am trying to do this:

protocol Fly {
}

class Bird: Fly {
}

func fetch<T: Fly>(model: T) {
    print("Done")
}

let bird: Fly = Bird()
fetch(model: bird)

However I get this error:

Cannot invoke 'fetch' with an argument list of type '(model: Fly)'

I set let bird: Fly = Bird() to be of type Fly, shouldn't it work since the function fetch takes any object that conforms to that protocol?

Any thoughts?

4
  • If you are using protocol the syntax to do this is func fetch<T>(model: T) where T: Fly. What you have typed is for subclassing I believe. But still it shows same error. Commented Aug 3, 2017 at 5:22
  • @adev Thanks for pointing that out! Yeah still same error thought : ( Commented Aug 3, 2017 at 5:24
  • Any reason why you are not doing this -> func fetch(model: Fly) That will work fine, Commented Aug 3, 2017 at 5:24
  • I will be using a library and might need to combine this function with it (unless not necessary but not sure at the moment). Wanted to see ideas as to what I'm doing wrong since I don't have experience with generics Commented Aug 3, 2017 at 5:26

2 Answers 2

5

You are creating with Fly object with Bird instance

Replace code

protocol Fly {
}

class Bird: Fly {
}

func fetch<T: Fly>(model: T) {
    print("Done")
}

let bird: Bird = Bird() // Here is a problem 
fetch(model: bird)
Sign up to request clarification or add additional context in comments.

10 Comments

I know about that, but why can't I have this let bird: Fly = Bird() and pass that into the function if the function accepts any instance that conforms to Fly?
Fly Protocol doesn't confirm Fly it self . Bird does
Oh that makes sense. Is there a way then to make the function fetch accept any type of type Fly? Or that doesn't make sense - not sure?
You can pass any class object that confirms protocol Fly as argument.
let bird: Fly = Bird() is perfectly fine. I don't think that is the issue here.
|
2

I set let bird: Fly = Bird() to be of type Fly, shouldn't it work since the function fetch takes any object that conforms to that protocol?

The overload resolution of the fetch(model: bird) call is done statically at compile time. The bird instance has been explicitly annotated to be of type Fly (which happens to be a protocol which can hold, dynamically, instances conforming to it). Since protocols doesn't conform to themselves, a call to fetch(model: bird) will not be eligable to use the constrained generic method func fetch<T: Fly>(model: T), since the type of bird, namely Fly, does not fulfill the type constraint T: Fly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.