当前位置 : 主页 > 手机开发 > 其它 >

合并类的数组中的数组

来源:互联网 收集:自由互联 发布时间:2021-06-11
下面的类里面有一些变量. class Person { var age: Int = 4 var items = [String]()} var allPeople = [Person]()var allItems = [String]() 假设我们为类创建了初始化器并且allPeople中有n个元素,我想将每个对象的所有
下面的类里面有一些变量.

class Person {
    var age: Int = 4
    var items = [String]()
} 

var allPeople = [Person]()
var allItems = [String]()

假设我们为类创建了初始化器并且allPeople中有n个元素,我想将每个对象的所有项合并为一个新数组

当我尝试访问allPeople的每个索引时,问题出现了,并从那里获取items变量并将其附加到allItems.但是我需要指定一个根据元素总数而变化的数字.我最初的尝试是使用for循环.还使用allPeople [allPeople.count – n],类似于此.

solution1(这是最快捷的方式):

//if you want to keep adding to the old array
allItems += allPeople.flatMap{$0.items}

//if you want to add into a new array
let newArray = allItems + allPeople.flatMap{$0.items}
// Using 'map' won't work:
allItems = allItems + allPeople.map{$0.items} //error: binary operator '+' cannot be applied to operands of type '[String]' and '[[String]]'

上面的代码不起作用,因为我们将[String]添加到[String],它不知道如何处理,读取:

let john = Person()
john.items = ["a", "b", "c"]

let jane = Person()
jane.items = ["d", "e", "f"]

allPeople.append(john)
allPeople.append(jane)

print(allPeople.map{$0.items}) // [["a", "b", "c"], ["d", "e", "f"]] <-- [[String]] 
// and obviously can't be added to [String]

它在数组中打印数组.所以我们需要再做一步.

let mapped = allPeople.map{$0.items}

print(Array(mapped.joined())) // ["a", "b", "c", "d", "e", "f"]

所以如果我们想使用map,我们也应该使用join

解决方案2(不是很开心,但我只想解释一个flatMap基本上是一个连接图)

let newJoinedMappedArray = allItems + Array(allPeople.map($0.items).joined())
网友评论