Merge arrays in an array of a class

The next class has some variables inside it.

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

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

Assuming we created the initializers for the class, but allPeoplehas nelements in it, I would like to combine all the elements for each object into a new array

The problem arises when I try to access each index allPeople, and from there get the items variable and add it to allItems. But I need to specify a number that changes according to the total number of elements. My initial attempt was to use a for loop. Also using allPeople[allPeople.count - n]something like this.

+4
source share
3 answers

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, joined

solution2 ( , , a flatMap - join + map)

let newJoinedMappedArray = allItems + Array(allPeople.map($0.items).joined())
+4

, , , item Person allPeople allItems, :

for person in allPeople {
    allItems.append(contentsOf: person.items)
}
+1

try it

for person in allPeople {
    for item in person.items {
        allItems.append(item)
    }
}
0
source

Source: https://habr.com/ru/post/1662768/


All Articles