【发布时间】:2014-12-03 17:52:33
【问题描述】:
请参阅下面的自包含示例。编译器在最后一行(标记为COMPILE ERROR)报告错误,我将SimpleTrain 的实例分配给它(根据我的最佳判断)符合的协议类型。我怎样才能让它编译?我究竟做错了什么?还是这个编译器的问题?
protocol Train {
typealias CarriageType
func addCarriage(carriage: CarriageType)
func shortTrain<ShortType: Train where ShortType.CarriageType == CarriageType>() -> ShortType
}
class SimpleTrain<T> : Train {
typealias CarriageType = T
private var carriages: [T] = [T]()
func addCarriage(carriage: T) {
carriages.append(carriage)
}
func shortTrain<ShortType: Train where ShortType.CarriageType == CarriageType>() -> ShortType {
let short = SimpleTrain<T>()
short.addCarriage(carriages[0])
return short //COMPILE ERROR: SimpleTrain<T> is not convertible to 'ShortType'
}
}
编辑:即使我明确地将上面shortTrain 的返回类型向下转换(因此上面的最后一行代码sn-p 读取为return short as ShortType)为suggested by Antonio,仍然有编译调用函数shortTrain时出错:
let s = SimpleTrain<String>()
s.addCarriage("Carriage 1")
s.addCarriage("Carriage 2")
let a = s.shortTrain() //ERROR: Cannot convert the expression's type '()' to type 'Train'
let b = s.shortTrain<SimpleTrain<String>>() //ERROR: cannot explicitly specialize a generic function
【问题讨论】:
标签: ios generics swift interface compiler-errors