【问题标题】:Subscript an Arrary of generics type: error: Cannot subscript a value of type '[T]'泛型类型的下标和数组:错误:无法下标“[T]”类型的值
【发布时间】: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


【解决方案1】:

问题不在于下标。这是关于类型转换的。斯威夫特给出了一个误导性的错误信息。看看这一行:

someObject.item = items[index]
    AnyObject ^   ^ Mappable

Swift 不会将Mappable 隐式转换为AnyObject。相反,您必须使用强制转换:

func someFunction() {
    // Assuming `index` is an Int
    someObject.item = items[index] as! AnyObject
}

【讨论】:

    【解决方案2】:

    这只是您班级中的一个小变化。看看那个!

    class SomeClass<T: Mappable>{
        var items:[T] = []
        func getSomeItem(index:Int) -> T{
            return self.items[index] as T // no error
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 旁注:as T 是多余的,编译器知道类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2012-11-04
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多