How to check if String Int is in Swift?

I have a TextField that I want to check if the entered text is an integer. How could I do this?

I want to write a function like this:

func isStringAnInt(string: String) -> Bool { } 
+14
source share
4 answers

String Extension and Computed Property

You can also add a computed property to String .

The logic inside the computed property is the same as OOPer

 extension String { var isInt: Bool { return Int(self) != nil } } 

Now you can

 "1".isInt // true "Hello world".isInt // false "".isInt // false 
+25
source

Use this function

 func isStringAnInt(string: String) -> Bool { return Int(string) != nil } 
+21
source

You can check it like

 func isStringAnInt(stringNumber: String) -> Bool { if let _ = Int(stringNumber) { return true } return false } 

OR

you can create an extension for String. Go to File -> New File -> Swift File

In the newly created Swift file you can write

 extension String { func isStringAnInt() -> Bool { if let _ = Int(self) { return true } return false } } 

Thus, you can access this function throughout your project, for example,

 var str = "123" if str.isStringAnInt() // will return true { // Do something } 
+1
source
 if s is String { print("Yes, it a String") } else if s is Int { print("It is Integer") } else { //some other check } 
0
source

All Articles