有些东西想着很简单,写的时候一下子又写不出来,尴尬😓!
方法一
/// 一维数组转二维数组
/// - Parameters:
/// - oneDArray: 一维数组
/// - rawCount: 被分割的个数
/// - Returns: 转换后的二维数组
private func convertToTwoDArrayFrom(oneDArray: [Any], rawCount: Int) -> [[Any]] {
let twoDArray = stride(from: 0, to: oneDArray.count, by: rawCount).map { (index) -> [Any] in
if (index + rawCount) > oneDArray.count {
return Array(oneDArray[index...])
} else {
return Array(oneDArray[index..<index + rawCount])
}
}
print("转换后的二维数组\(twoDArray)")
return twoDArray
}
方法二
private func convertToTwoDArrayFrom(oneDArray: [Any], rawCount: Int) -> [[Any]] {
let totalCount = oneDArray.count
var lineNum: Int = 0
if totalCount % rawCount == 0 {
lineNum = totalCount / rawCount
} else {
lineNum = Int(floor(Float(totalCount) / Float(rawCount) + 1.0))
}
var twoDArray: [[Any]] = []
for index in 0..<lineNum {
let tempArray = Array(oneDArray[(index * rawCount)..<(index * rawCount + rawCount)])
twoDArray.append(tempArray)
}
return twoDArray
}
网友评论