Generics function return type issue with protocol - Swift

Viewed 37

I'm studying on generics in Swift and for testing some situations I have this struct and protocol:

protocol Vehicle {
    var name: String { get }
}

struct Car: Vehicle {
    let name = "car"
}

Then I have this function, and I would to return Car object but I have this function's signature:

func wash<T : Vehicle>(_ vehicle: T) -> T{
    return Car()
}

but I don't understand because I get this error:

Cannot convert return expression of type 'Car' to return type 'T'

If I return in this way I remove the error:

return Car() as! T

Why? Car is already a T type because in the function's signature I insert the constraint that T must be a Vehicle type.

0 Answers
Related