2017-06-24 40 views
0

雖然嘗試獲取子陣列與當時給定的範圍這個錯誤。嘗試獲得子陣列與給定的範圍

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

您需要爲您的信息類添加自定義下標。更多參考:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-ID305 – KKRocks

回答

1
let currentData = [Info(), Info(), Info()] 
let subarr0 = currentData[0..<2] // ArraySlice<Info> 
let subarr1 = Array(currentData[0..<2]) // Array<Info> 
-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]