Diego Alcubierre
Diego Alcubierre

Reputation: 95

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

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.

Upvotes: 2

Views: 2136

Answers (1)

jnpdx
jnpdx

Reputation: 52337

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.

Upvotes: 2

Related Questions