Home > Back-end >  map inside map error? move the index outside
map inside map error? move the index outside

Time:11-14

for example. I have two array for DataModel

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

another two array for DataModel2

let array3 = ["one","two","three"]
let array4 = ["one","two","three"]

my DataModel is

struct DataModel: Hashable{
        var image:String
        var name:String
        var dataModel2:[DataModel2]
}
struct DataModel2: Hashable{
        var image2:String
        var name2:String
}

I use the map method

convermodel = (0..<array2.count).map{
            index1 in
            datamodel(DataModel(image: array1[index], name: array2[index]) 
, dataModel2: (0..<array3.count).map{ index2 in
            DataModel2(image: array1[index2], name: array2[index2]) 
            
        }}

the compliyer call "Expected expression in list of expressions" " try breaking up the expression into distinct sub-expressions"

so how can i move index2 to the outside ??

CodePudding user response:

Based on Joakim Danielson's answer in your previous question you can do it without any loop by zipping the arrays

let converModel = zip(array3, array4)
    .map{ DataModel(image: $0.0, name: $0.1, dataModel2: zip(array1, array2).map(DataModel2.init)) }
  • Related