Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a String is an Int in Swift?

Tags:

swift

swift2

I have a TextField which I want to verify if the inputted text is an integer. How could I do this?

I want to write a function like this:

func isStringAnInt(string: String) -> Bool {  } 
like image 1000
Kasper Avatar asked Jul 02 '16 11:07

Kasper


People also ask

How do you check if a string is an integer in Swift?

You might want to make isStringAnInt() a computed property extension String { var isInt: Bool { if let _ = Int(self) { return true } return false } } , then you can do "123". isInt .

How do I convert a string to an int in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do you check if a string is alphanumeric in Swift?

In Swift, how can I check if a String is alphanumeric, ie, if it contains only one or more alphanumeric characters [a-zA-Z0-9] , excluding letters with diacritics, eg, é.

How do you get the first character of a string in Swift 5?

In Swift, the first property is used to return the first character of a string.


2 Answers

String Extension & Computed Property

You can also add to String a computed property.

The logic inside the computed property is the same described by OOPer

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

Now you can

"1".isInt // true "Hello world".isInt // false "".isInt // false 
like image 140
Luca Angeletti Avatar answered Sep 19 '22 15:09

Luca Angeletti


Use this function

func isStringAnInt(string: String) -> Bool {     return Int(string) != nil } 
like image 28
OOPer Avatar answered Sep 20 '22 15:09

OOPer