0

I'm trying to ForEach a 2D array based on this answer here:

SwiftUI ForEach get element AND index in 2d array

ForEach(0..<memesSplit.endIndex) { index in
    
    ForEach(memesSplit[index], id: \.memeid){_ in
        
    }
    
}

and get this warning:

Non-constant range: argument must be an integer literal

I looked it up and it means the app will crash because of "out of index" in case an item will be removed.

So how to do this correctly?

When I do what I've tried first:

ForEach(memesSplit) { arr in
    
    ForEach(arr, id: \.memeid){ meme in
        
    }
    
}

then I get this error:

Referencing initializer 'init(_:content:)' on 'ForEach' requires that '[MemeModel]' conform to 'Identifiable'

Based on the mentioned question I tried:

ForEach(self.memeModel.memesSplit) { arr in

    ForEach(arr, id: \.memeid){ meme in

    }

}

And couple other syntaxes but get all kind of other errors where I don't know what they mean

This is the model of the inner array:

struct MemeModel: Codable {
    var memeid: Int
    var title: String
    var pic: String
    var size: String
    var userid: Int
    var nickname: String
    var commentcount: Int
    var time: Int
    var secondsago: Int
    var checked: Int
    var liked: Int
    var disliked: Int
    var saved: Int
    var voteup: Int
    var votedown: Int
}

and this is how I declare the 2D array:

@State private var memesSplit = [[MemeModel]]()
6
  • Does this answer your question? Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Planet' conform to 'Identifiable' Commented Nov 27, 2022 at 22:27
  • I've seen this, no it does not Commented Nov 27, 2022 at 22:40
  • Please check out what I just added to the question at the end, do you an that? It looks like the question you all are keep referring to is a normal custom array, not multidimensional/2D @jnpdx Commented Nov 27, 2022 at 22:52
  • You could create a new wrapper type (MemeSection?) that stores an array of MemeModels and have it conform to Identifiable. Commented Nov 27, 2022 at 22:59
  • This is the normal way and I'm aware of it but I need what I'm asking and it's too much and actually unnecessary to explain why I need it that way Commented Nov 27, 2022 at 23:03

0

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.