NSMutableArray *sample;
我有一個NSmutableArray
,我想分割成塊。我試圖檢查互聯網沒有找到它的解決方案。我得到了拆分整數數組的鏈接。如何將`NSmutableArray`數組數組拆分爲swift 3?
NSMutableArray *sample;
我有一個NSmutableArray
,我想分割成塊。我試圖檢查互聯網沒有找到它的解決方案。我得到了拆分整數數組的鏈接。如何將`NSmutableArray`數組數組拆分爲swift 3?
您可以使用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))
你可以提供我的解決方案在swift 3 – technoAndroid
我越來越範圍延伸bounds.how來處理it.if der是沒有索引 – technoAndroid
我的數組範圍是772.但它給出了錯誤,指數範圍{392,441}延伸超出界限[0 .. 772]'.. – technoAndroid
這怎麼樣,這是更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]]
不可用於整數數組不適用於nsmutablearray或nsarray – technoAndroid
@technoAndroid您可以將NSMutableArray轉換爲Swift數組......我更新了我的答案。 – brianLikeApple
感謝您的幫助brianlikeApple,但我需要nsmutablearray本身..特定目的,我使用它 – technoAndroid
請更新參照問題'NSMutableArray'和預期'output' 。 –