相关疑难解决方法(0)

无法将类实例分配给其协议类型?

请参阅下面的自包含示例.编译器在最后一行(标记为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'
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:即使我明确地向下转换shortTrain上面的返回类型(以便上面的代码片段的最后一行读取return short as ShortType …

generics compiler-errors interface ios swift

5
推荐指数
1
解决办法
2527
查看次数

标签 统计

compiler-errors ×1

generics ×1

interface ×1

ios ×1

swift ×1