The answer to your question depends on what you want to do with your data once you're in the second view.
If you plan on just spitting out information in the second view, without modifying it, then you can pass the data to your second view through the view struct's initializer.
Method 1: The simpler, non-binding solution
Keep track of all your String inputs using your array
variable, wrapped with @State
.
struct InputView: View {
@State var array: [String] = []
var body: some View {
// Add your list of string inputs here,
// as well as your Append button...
}
}
In your second view, have a property for the String you want to display (with no initialized value).
struct OutputView: View {
var displayString: String
var body: some View {
// Display your String here using Text...
}
}
Then, in your InputView
's body
, pass a random element from array
into OutputView
. In case your array has no elements, you should consider passing a default value.
NavigationLink(destination: OutputView(displayString: array.randomElement() ?? "none") {
Text("To next page")
}
Method 2: Using Binding to modify in another View
If you need to modify the value after it's passed into your OutputView
, consider using Binding
.
In your InputView
, you can pass the entire array as a Binding<Array<String>>
into your OutputView
, provided that OutputView
is prepared to handle a Binding
variable using a @Binding
wrapper in your class implementation.
struct OutputView: View {
@Binding var array: [String]
// Display a random element from array here.
// When you modify array, it will also modify the array
// property that belongs to InputView.
var body: some View {
// ...
}
}
You'll need to use the $
operator to pass the array as Binding<>
.
struct InputView: some View {
@State var array: [String] = []
var body: some View {
// ...
NavigationLink(destination: OutputView(array: $array) {
Text("To next page")
}
// ...
}
}