Have any Question?

You can ask below or enter what you are looking for!

How to check that a string object contains only numbers

You should always validate data entered by user or received from backend before doing any processing on it, for example if you are expecting a string object that contains a price or quantity then this string must include only digits.
I will show you a simple way of validating that a string object contains only numbers here:

    func isStringContainsOnlyNumbers(string: String) -> Bool {
        return string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
    }

As you see we search the string for any non-digit character- this is why we used inverted– and if the result is nil then all characters in the string object are digits and the function returns true, otherwise it returns false

Now we can use this function like this

        if isStringOnlyNumbers(string: "123abc") {
            print("true")
        } else {
            print("false")
        }

Leave a Reply

Your email address will not be published. Required fields are marked *