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

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
}

Use this function

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

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

Tags:

Swift

Swift2