OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Numbers In Swift

Code snippet for how to Check If A String Contains Only Numbers In Swift with sample and detail explanation

In Swift programming, there may come a point where you need to check if a string contains only numbers. The following article presents a simple guide to achieving this using Swift language.

Code snippet for Checking If A String Contains Only Numbers

import Foundation

func isStringOnlyContainNumbers(input: String) -> Bool {
    for character in input {
        if !character.isNumber {
            return false
        }
    }
    return true
}

let stringToCheck = "12345"
print(isStringOnlyContainNumbers(input: stringToCheck))

Code Explanation for Checking If A String Contains Only Numbers

Step 1: Import the Foundation framework. This is a Swift package that provides fundamental software services useful to application services, application environments, and to other frameworks.

import Foundation

Step 2: Define the function isStringOnlyContainNumbers. This function takes a String as an input and returns a Boolean.

func isStringOnlyContainNumbers(input: String) -> Bool {

Step 3: Loop through each character within the input string.

for character in input {

Step 4: Check if the character is not a number. In Swift, there is a built-in property isNumber which returns true if the character represents a number and false otherwise. If the character is not a number, then return false, otherwise, process the next character.

if !character.isNumber {
    return false
}

Step 5: After checking all characters, it means that all are numbers. Thus, return true.

return true

Step 6: Close the function.

}

Step 7: Now you can use the created function, isStringOnlyContainNumbers, to check whether a given string contains only numbers.

let stringToCheck = "12345"
print(isStringOnlyContainNumbers(input: stringToCheck))

In this case, the string “12345” is composed only by numbers, hence the function will return true.

Hence, following this step-by-step guide, you should be able to efficiently check in Swift if a string contains only numbers.

swift