Reputation: 15
How can i check through an if-statement if a TextField is an integer or not ?
@IBAction func Clickme2(sender: AnyObject) {
if TextField2.text == Int() {
}
Upvotes: 0
Views: 69
Reputation: 6369
If you want to check " 1 2 3 " as int,you can do like this:
@IBAction func Clickme2(sender: AnyObject) {
var text = TextField2.text.stringByReplacingOccurrencesOfString(" ", withString: "")
if let integer = Int(text) {
// do something here
}
}
If you only want to check " 123 " as int,you can do like this:
@IBAction func Clickme2(sender: AnyObject) {
var text = TextField2.text.stringByTrimmingCharactersInSet(.whitespaceCharacterSet())
if let integer = Int(text) {
// do something here
}
}
Upvotes: 0
Reputation: 2210
if ( Int(textField2.text) == nil) {
//In this case, your text is not an integer
}
This works perfectly fine since Swift has those fancy failable Initializers which prevent your app from crashing when you pass invalid parameters
Upvotes: 0
Reputation: 236275
You can check it the textField text property is not nil and if it can be converted to Int:
guard let text = textField2.text, integer = Int(text) else { return }
print(integer)
If you just need to know if it text property has an Integer you can create a computed property to return true or false as follow:
extension UITextField {
var isInteger: Bool {
guard let text = text else { return false }
return Int(text) != nil
}
}
usage:
if textField2.isInteger {
// do whatever
}
Upvotes: 1