当尝试获取子数组时,给定范围此错误。
Cannot subscript a value of type '[Info]' with an index of type 'CountableRange<Int>' .
我的代码是
信息模式
class Info : NSObject {
var type : Type = .Unknown
var data = ""
init() {
super.init()
}
}
数组声明
var currentData : [Info] = []
尝试此代码时
let moreAnimals: [Info] = self.currentData[0..<5] //above error disply.
答案 0 :(得分:1)
let currentData = [Info(), Info(), Info()]
let subarr0 = currentData[0..<2] // ArraySlice<Info>
let subarr1 = Array(currentData[0..<2]) // Array<Info>
答案 1 :(得分:-2)
从泛型集合中获取元素范围,我们需要转换为NSArray并使用subarrayWithRange方法获取范围内的元素。
var moreAnimals: [Int] = [1,2,3,4,5,6,7,8,9,10]
var otherarr: [Int] = (moreAnimals as NSArray).subarray(with: NSMakeRange(0, 5)) as! [Int]
输出:: [1,2,3,4,5,6,7,8,9,10]
[1,2,3,4,5]