Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to merge two array to model array?

for example. I have two array

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

my datamodel is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])]

>Solution :

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]) 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading