0

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

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

You could even simply write .map ( DataModel.init ).
@vadian thanks a lot. I didn’t even consider that since the input was a tuple, I learned something new now.
1

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

3 Comments

This is just reimplementing zip.
@Jessy except it crashes when the shorter of the two arrays reaches its end
Yep, zip is better. Good catch! Zip should use the shorter of the two just as this does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.