I'm studying generics and "some" keyword in Swift and for testing I have this situation:
protocol Vehicle {
var name: String { get }
}
struct Car: Vehicle {
let name = "car"
}
struct Bus: Vehicle {
let name = "bus"
}
Then I tried to create some functions for testing various scenario:
func wash<T : Vehicle>(_ vehicle: T, x : Int) -> T{
if(x < 10){
return Car() as! T
}
return Bus() as! T
}
This function is ok and I know why.
If I change it using "some":
func wash<T : Vehicle>(_ vehicle: T, x : Int) -> some Vehicle{
if(x < 10){
return Car()
}
return Bus()
}
I get this error:
Function declares an opaque return type 'some Vehicle', but the return statements in its body do not have matching underlying types
My question is: both functions I wrote that I want to get Vehicle object, why the second is wrong? (I thought maybe the "some" keyword wants to know the object type to compile time and because there is "if" in the body, it can determinate only runtime, but I don't know).
For resolve the second function problem I tried to use "any", but I don't know because I don't get the error:
func wash<T : Vehicle>(_ vehicle: T, x : Int) -> any Vehicle{
if(y < 10){
return Car()
}
return Bus()
}
Can you explain this difference?