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      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.