UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)")

              }

2      

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)
        }
    }
}

2      

Thanks for your help, I learned a lot

2      

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)

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.