Home > Back-end >  how to merge two array to model array?
how to merge two array to model array?

Time:11-14

for example. I have two array

let array1 = ["one","two","three"]
let array2 = ["one","two","three"]

my datamodel is

struct datamodel: Hashable{
        var image:String
        var name:String
}

how can I merge two arrays into the model array

dataarray = [datamodel(image:array1[0],name:array2[0])]

CodePudding user response:

You can use zip to merge the two arrays into an array of tuples and map to map the tuple to your type

let models = zip(array1, array2).map(DataModel.init)

CodePudding user response:

So the first array contains values for image and the second values for name?

You could iterate through them both at the same time and map those values to the model (let's call it DataModel to be a bit Swiftier). You could only have as many results as the the count of the smaller of the two arrays, so you could try:

let dataArray = (0..<min(array1.count, array2.count))
    .map { DataModel(image: array1[$0], name: array2[$0]) }

Put a little more verbosely:

let minCount = min(array1.count, array2.count)

let dataArray = (0..<minCount).map { index in
    DataModel(image: array1[index], name: array2[index]) 
}
  • Related