Cannot convert [Int] to [Int] in generic implementation

老子叫甜甜 提交于 2020-01-03 18:31:31

问题


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
    }
}

回答1:


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]'


来源:https://stackoverflow.com/questions/33891280/cannot-convert-int-to-int-in-generic-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!