Reputation: 41
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 !
Upvotes: 0
Views: 610
Reputation: 345
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.
Upvotes: 1