简体   繁体   中英

How to concatenate specific String from Array ? [SwiftUI]

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 !

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM