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

Store textfield data as integer

Forums > SwiftUI

hey guys, I have some problem with storing the input number as integer in swiftui. i have already declared num as 0 and I wish the input number stored on num but the text always show 0, seems data didnt store on num. How to fix it? Many thanks

var num = 0 VStack {

            TextField("Please Enter your cost in HKD", value: $cost, formatter: NumberFormatter())

                .keyboardType(.numberPad)

                .padding()

                    .overlay(RoundedRectangle(cornerRadius: 100).stroke(Color.blue, lineWidth: 1))

                    //.keyboardType(.numberPad)

                    //.padding()

                 Button("Store Cost")

                        {

                    num = Int(cost)

                 }

            Text("\(num*3)")

              }

   

Hi @him1202

Your num (number) variable need to be @State and not in the body of View. You are converting from a string to a Int therefore you need to handle that. I have just used nil coalescing however you should tell user that entered incorrect format. You do have an extra call in TextField of formatter: NumberFormatter() See below

struct ContentView: View {
    @State var cost = ""
    @State var number = 0

    var body: some View {
        VStack {
            TextField("Please Enter your cost in HKD", text: $cost)
                .keyboardType(.decimalPad)
                .padding(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 100)
                        .stroke(Color.blue, lineWidth: 1)
                )
                .padding()
            Button("Calculate") {
                number = Int(cost) ?? 0
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.primary)
            .cornerRadius(30)

            Text("\(number * 3)")
                .padding()
                .font(.largeTitle)
        }
    }
}

However I might do something like this

struct ContentView: View {
    @State var cost = ""

    var number: String {
        guard let cost = Int(cost) else {
            return "Use numbers only"
        }

        return String(cost * 3)
    }

    var body: some View {
        VStack {
            TextField("Please Enter your cost in HKD", text: $cost)
                .keyboardType(.decimalPad)
                .padding(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 100)
                        .stroke(Color.blue, lineWidth: 1)
                )
                .padding()

            Text(number)
                .padding()
                .font(.largeTitle)
        }
    }
}

   

Thanks for your help, I learned a lot

   

You may also wish to consider using the currency format.


/// If a number returns it as a Double type
extension String {
    func toDouble() -> Double? {
        return NumberFormatter().number(from: self)?.doubleValue
    }
}

let currencyFormat: NumberFormatter = {
    let currencyFormat = NumberFormatter()
    currencyFormat.numberStyle = .currency

    return currencyFormat
}()

func cashFormat (amount: Double) -> String {   // Double as some currencies have fractional units - dollars & cents, pounds & pence
    return currencyFormat.string(from: NSNumber(value: amount))!
}

Text("\cashFormat(amount: number.toDouble() ?? 0.0)" )   // nil coalescing as 'number' may not actually be a number
     .padding()
     .font(.largeTitle)

   

Hacking with Swift is sponsored by Stream

SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.

Go to GitHub

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.