【发布时间】:2016-02-06 11:50:27
【问题描述】:
如何解决这个问题?
protocol Mappable {
...
}
class Foo {
item:AnyObject
}
class SomeClass<T:Mappable> {
var someObject = Foo()
var items:[T]
...
func someFunction() {
someObject.item = items[index] // error: Cannot subscript a value of type '[T]'
}
我尝试为下标添加扩展名 [T] 但失败了:
extension Array where Element:Mappable {
subscript(index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
更新:这是一条误导性错误消息,请参阅下面的答案
【问题讨论】:
-
错误信息具有误导性。只需在方法中添加一个返回类型。不需要扩展。
-
请不要添加问题的答案。 SO 格式为问题+答案。
标签: arrays swift generics subscript