Trying to create a generic data source I bumped into this error and I was wondering why this isn't compilable.
The error:
Cannot convert return expression of type '[Int]' to return type '[Int]'
The code:
protocol DataSource {
func getData<T> () -> [T]
}
class IntDataSource<Int>: DataSource {
let data:[Int] = []
func getData<Int>() -> [Int] {
return data
}
}
The error is thrown on the return statement in IntDataSource.
I know this could be done in better ways with
typealias DataType
var data: DataType? { get }
But I'm mainly interested in why the compiler doesn't want to accept the return statement. Any ideas?
EDIT:
Part of the question is also why if the previous code is not compilable is the following fair game?
class IntDataSource<Int>: DataSource {
func getData<Int>() -> [Int] {
let data:[Int] = []
return data
}
}
EDIT 2:
This version also compiles without issues
class IntDataSource<Int>: DataSource {
func getData<Int>() -> [Int] {
return getIntData()
}
func getIntData<Int>() -> [Int] {
let data:[Int] = []
return data
}
}
The "strange" compiler error
Cannot convert return expression of type '[Int]' to return type '[Int]'
can be explained as follows:
Both the <Int>
in your class definition and the <Int>
in the method definition introduce a new generic type placeholder called Int
(and therefore the outer <Int>
hides the global type with the same name, and the inner <Int>
hides the outer one). Your class definition is equivalent to
class IntDataSource<A>: DataSource {
let data:[A] = []
func getData<B>() -> [B] {
return data
}
}
And now the compiler error is understandable:
cannot convert return expression of type '[A]' to return type '[B]'
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments