Home > database >  How to test whether a value is of type Int
How to test whether a value is of type Int

Time:12-24

I have a Textfield and I want to test whether the its input value is of type Int or not.

Here's the code:

import SwiftUI

struct ContentView: View {
    @State var integer: String = ""
    
    var body: some View {
        TextField("Enter an integer", text: $integer)
        
        Button(action: {
            if (Int(integer)//here is where I want to figure out whether the value is of type Int) {
                print("Yay")
            } else {
                print("not an integer")
            }
        }, label: {
            Text("Check")
        })
    }
}

There's gotta be a simple way to do this but I haven't been able to figure it out.

CodePudding user response:

Simple null checking will work.

Button(action: {
    if Int(integer) != nil {
        print("Yay")
    } else {
        print("not an integer")
    }
}, label: {
    Text("Check")
})

Or with optional binding

Button(action: {
    if let numInt = Int(integer) {
        print("Yay")
        print(numInt)
    } else {
        print("not an integer")
    }
}, label: {
    Text("Check")
})

CodePudding user response:

You can use Int(integer) and unwrap the optional as following:

if let intValue = Int(integer) {
    print("Int value: \(intValue)")
} else {
    print("Not an int")
}
  • Related