2017-07-05 66 views

回答

1

您可以使用subarray方法。

let array = NSArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 

let left = array.subarray(with: NSMakeRange(0, 5)) 
let right = array.subarray(with: NSMakeRange(5, 5)) 
+0

你可以提供我的解決方案在swift 3 – technoAndroid

+0

我越來越範圍延伸bounds.how來處理it.if der是沒有索引 – technoAndroid

+0

我的數組範圍是772.但它給出了錯誤,指數範圍{392,441}延伸超出界限[0 .. 772]'.. – technoAndroid

1

這怎麼樣,這是更Swifty?

let integerArray = [1,2,3,4,5,6,7,8,9,10] 
let stringArray = ["a", "b", "c", "d", "e", "f"] 
let anyObjectArray: [Any] = ["a", 1, "b", 2, "c", 3] 

extension Array { 
    func chunks(_ chunkSize: Int) -> [[Element]] { 
     return stride(from: 0, to: self.count, by: chunkSize).map { 
      Array(self[$0..<Swift.min($0 + chunkSize, self.count)]) 
     } 
    } 
} 

integerArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 
stringArray.chunks(3) //[["a", "b", "c"], ["d", "e", "f"]] 
anyObjectArray.chunks(2) //[["a", 1], ["b", 2], ["c", 3]] 

轉換NSMutableArray斯威夫特Array

let nsarray = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 
if let swiftArray = nsarray as NSArray as? [Int] { 
    swiftArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 
} 

如果你想堅持使用NSArray,則:

let nsarray = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 

extension NSArray { 
    func chunks(_ chunkSize: Int) -> [[Element]] { 
     return stride(from: 0, to: self.count, by: chunkSize).map { 
      self.subarray(with: NSRange(location: $0, length: Swift.min(chunkSize, self.count - $0))) 
     } 
    } 
} 

nsarray.chunks(3) //[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] 
+0

不可用於整數數組不適用於nsmutablearray或nsarray – technoAndroid

+0

@technoAndroid您可以將NSMutableArray轉換爲Swift數組......我更新了我的答案。 – brianLikeApple

+0

感謝您的幫助brianlikeApple,但我需要nsmutablearray本身..特定目的,我使用它 – technoAndroid