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 show a String Array in SwiftUI

I’m building an educational app, where I have come categories and then show the stories inside each category.

The use I’m experiencing is how to show a String Array. I can show Strings without any issue. Hope you can help.

Here is the detailed view code that is working and showing the "lesson" (story in this case):

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 StoryDetailView: View {
    
    @EnvironmentObject var model: ContentModel
    
    var body: some View {
        
        let story = model.currrentStory
        
        VStack {
            Image(story?.featuredImage ?? "effort")
                .resizable()
                .scaledToFit()
            Text(story?.title ?? "error")
            Text(story?.description ?? "error description")
            
        }
        
    }
}

I tried this code to show the "explanation", in my case is called "text".

ForEach(0..<(story?.text.count ?? ""), id: \.self) { index in
                
                Text(story?.text[index] ?? "notext")
                    .padding(.bottom, 5)
            }

I get this error in the "ForEach" line: Cannot convert value of type ‘String’ to expected argument type ‘Int’

If I force-unwrap instead of using ‘??’, the app crashes.

>Solution :

Instead of using indices, you should iterate over the array itself in the ForEach:

ForEach(story?.text ?? []), id: \.self) { item in
  Text(item).padding(.bottom, 5)
}

Beware, though that using .self on a ForEach id will fail or produce unexpected results if the array elements aren’t truly unique. Consider creating a data model with truly unique Identifiable elements.

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