Swift

Swift 分割数组

用下面的方法可以把一维数组,分割成二维数组

extension Array {
    func split() -> [[Element]] {
        var resultArray: [[Element]] = []
        var beginIndex = 0
        var endIndex = 4
        var count = self.count

        while count >= 4 {
            resultArray.append(Array(self[beginIndex ..< endIndex]))
            beginIndex += 4
            endIndex += 4
            count -= 4
        }

        if count < 4 {
            resultArray.append(Array(self[beginIndex ..< self.count]))
        }
        return resultArray
    }
}