Kasper
Kasper

Reputation: 13592

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

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 {

}

Upvotes: 33

Views: 32218

Answers (5)

Zain Ali
Zain Ali

Reputation: 15963

You can also use following extension method that use a different logic than all mentioned answers

extension String  {
    var isStringAnInt: Bool {
        return !isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
    }

Upvotes: 1

Taqi Ahmed
Taqi Ahmed

Reputation: 17

if s is String {
  print("Yes, it's a String")
} else if s is Int {
  print("It is Integer")
} else {
  //some other check
}

Upvotes: -3

Luca Angeletti
Luca Angeletti

Reputation: 59496

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

Upvotes: 71

Umair Afzal
Umair Afzal

Reputation: 5039

You can check like this

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

And in your newly created Swift file you can write

extension String
{
    func isStringAnInt() -> Bool {

        if let _ = Int(self) {
            return true
        }
        return false
    }
}

In this way you will be able to access this function in your whole project like this

var str = "123"
if str.isStringAnInt() // will return true
{
 // Do something
}

Upvotes: 1

OOPer
OOPer

Reputation: 47886

Use this function

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

Upvotes: 27

Related Questions