我想从这个二维数组创建一个数组
Image
答案 0 :(得分:1)
如果您只有这5个元素,并且只想用代码将它们分开,那么也可以通过简单的循环来实现。
var array1 = ["apples","oranges","grapes","vegetables","soups"]
var arraylist:[[String]] = [[String]]()
var innerArray: [String] = [String]()
var isFirstTime: Bool = true
for obj in array1 {
if isFirstTime {
innerArray.append(obj)
if innerArray.count == 3 {
arraylist.append(innerArray)
innerArray.removeAll()
isFirstTime = false
}
} else {
innerArray.append(obj)
if innerArray.count == 2 {
arraylist.append(innerArray)
innerArray.removeAll()
}
}
}
打印(数组列表)
结果:[[“苹果”,“橘子”,“葡萄”],[“蔬菜”,“汤”]]
答案 1 :(得分:0)
您编写的内容在Swift中完全有效。请考虑以下内容:
let apples = "apples"
let oranges = "oranges"
let grapes = "grapes"
let vegetables = "vegetables"
let soups = "soups"
var array1 = [apples, oranges, grapes, vegetables, soups]
var arraylist = [[apples, oranges, grapes], [vegetables, soups]]
现在添加这两种类型:
var array1: [String] = [apples, oranges, grapes, vegetables, soups]
var arraylist: [[String]] = [[apples, oranges, grapes], [vegetables, soups]]
通常,您可以创建定义数组拆分方式的组。检查以下内容:
// Constants
let apples = "apples"
let oranges = "oranges"
let grapes = "grapes"
let vegetables = "vegetables"
let soups = "soups"
// Groups of items
let groups: [[String]] = {
let fruits: [String] = [apples, oranges, grapes]
let misc: [String] = [vegetables, soups]
return [fruits, misc]
}()
// Array to seperate by group
let inputArray: [String] = [apples, oranges, grapes, vegetables, soups]
// Array of arrays of items per group. Outputs [["apples", "oranges", "grapes"], ["vegetables", "soups"]]
let grouppedArray: [[String]] = {
return groups.compactMap { group in
let filteredArray = inputArray.filter { group.contains($0) }
return filteredArray.isEmpty ? nil : filteredArray
}
}()