NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

User Input into Arrays in SwiftUI

Forums > SwiftUI

I have been trying to write code to enable a user to input integer data into an Array, I am struggling with what should be a simple operation.

The Array is an EnvironmentObject comprised of 20 Integers.

I would like the User to the prompted to enter integer data for each item in the Array, from a single view within the App.

Can anyone assist with the code for this, or point me to where I can learn this?



You can try something like this:

import SwiftUI

class InputFields: ObservableObject {
    @Published var inputs: [Int] =  Array(repeating: 0, count: 20)

struct TwentyInputView: View {
    //keep track of the Int values in the environment
    @EnvironmentObject var fields: InputFields

    //keep track of the current String values of our 20 text fields locally
    @State private var inputs: [String] = Array(repeating: "", count: 20)

    var body: some View {
        VStack {
            ForEach(fields.inputs.indices) { idx in
                TextField("Field \(idx)", text: $inputs[idx])
                    .onChange(of: inputs[idx]) { value in
                        //the value we get in is a String, so we need to
                        //convert it to an Int before we update the
                        //EnvironmentObject fields
                        fields.inputs[idx] = Int(value) ?? 0
            .onAppear {
                //load our EnvironmentObjects fields into the
                //local state and convert from String -> Int
                fields.inputs.indices.forEach { idx in
                    inputs[idx] = String(fields.inputs[idx])

struct TwentyInputView_Previews: PreviewProvider {
    static var previews: some View {


Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.