Alston
Alston

Reputation: 1226

Subscript an Arrary of generics type: error: Cannot subscript a value of type '[T]'

How to solve this problem?

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

I've tried adding an extension for subscripting [T] but fail:

extension Array where Element:Mappable {
    subscript(index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}

UPDATE: This is a misleading error message, please see answers below

Upvotes: 1

Views: 508

Answers (2)

Code Different
Code Different

Reputation: 93181

The issue isn't so much about subscripting. It's about type conversion. Swift gave a misleading error message. Take a look at this line:

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

Swift doesn't implicitly convert Mappable to AnyObject. Instead you must use a force cast:

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

Upvotes: 2

Sohel L.
Sohel L.

Reputation: 9540

Here is just the small change in your class. Just look at that!

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

Hope this helps!

Upvotes: 0

Related Questions