3

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.

5
  • Hi @jnpdx, yes story.text is a [String]. When it's a simple String, it's showing without issue. Commented Feb 4, 2022 at 21:18
  • I'm surprised the compiler lets you get away with story?.text.count ?? "" -- at the least, it should be story?.text.count ?? 0 where 0 is the default value, but regardless, see my answer about not relying on indices like this. Commented Feb 4, 2022 at 21:19
  • @jnpdx, thank you very much, solved Commented Feb 4, 2022 at 21:24
  • Great -- you can accept the answer by clicking the green checkmark Commented Feb 4, 2022 at 21:25
  • @jnpdx, done, thank you! Still learning how to use this ;) Commented Feb 4, 2022 at 21:27

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.