如何将`NSmutableArray`数组拆分为swunk 3?

时间:2017-07-05 09:49:49

标签: swift nsmutablearray

NSMutableArray *sample; 

我有一个NSmutableArray,我想把它拆分成块。我试过检查互联网没有找到解决方案。我得到了拆分整数数组的链接。

2 个答案:

答案 0 :(得分:2)

这对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转换为Swift 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]]

答案 1 :(得分: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))