arrays - Subscript an Arrary of generics type: error: Cannot subscript a value of type '[T]' -
how solve 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 value of type '[t]' }
i've tried adding extension subscripting [t]
fail:
extension array element:mappable { subscript(index: int) -> element? { return indices ~= index ? self[index] : nil } }
update: misleading error message, please see answers below
the issue isn't subscripting. it's type conversion. swift gave misleading error message. take @ line:
someobject.item = items[index] anyobject ^ ^ mappable
swift doesn't implicitly convert mappable
anyobject
. instead must use force cast:
func somefunction() { // assuming `index` int someobject.item = items[index] as! anyobject }
Comments
Post a Comment