0

I have an array :

struct Main: Identifiable {
    var id = UUID()
    var value: String
    var type: String
}
var mainArray = [Main]()

And I need to output the "var value" of each of the elements which are in this array into a Text("")

Like : Text("(main[index].value)")

But I don't know the correct way of doing that

Also, I wiil need to be able to tweak the value I get with a function like :

func readMain() -> String {
        if main[index].value == "specificContent" { return "Correct" }
        else { return "Incorrect"}
    }

And then add my Text(readMain()) but that return all the values from the array like : Text("Correct, Incorrect, Incorrect, Correct, Correct")

Any idea ?

Thanks in advance !

1 Answer 1

1

I think you are looking for something like this:

@State private var mainArray = [Main]()

var body: some View {
    ForEach(mainArray) { main in
        Text(
            main.value == "correctValue" ?
            "Correct" :
            "Incorrect"
        )
    }
}

This prints whether the value property (of each Main element in you mainArray) is "correct" seperately.

If you want, though, your text to appear in one line with a space character separating the different mainArray values you could do this:

@State private var mainArray = [Main]()

var body: some View {
    Text(
        mainArray
            .map {
                $0.value == "correctValue" ?
                    "Correct" :
                    "Incorrect"
            }
            .joined(separator: " ")
    )
}

In the above sample the mainArray is converted into an string array containing a description of whether the values are "correct" and then these values are joined into one string with the space character (" ") separating them.

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

1 Comment

Thanks for your answer, I think it getting close to the solution :) The "Correct" "Incorrect" thing was just an exemple, in fact the values in my Array could be : "book title 1", "movie title 2", "book title 2", etc... And I want to output : Text("book title 1, movie title 2, book title 2") I tried with your first exemple code by just writing "Text( main.value )" and it output all of the values which is cool, but I need to be able to separate the different values (using a point, or a comma, as I wish) Is it possible ? Thanks again !

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.