Swift Program to Check if a String is Numeric


To check if the given string is numeric or not we use Double() initializer in Swift Programming.

A string is an ordered collection of characters for example “Sky”. A string can be numeric and non-numeric. A numeric string is a string which only contains numbers for example “12345”. So the valid numeric strings are: “3423”, “222333”, “34.342”, etc., whereas non-valid numeric strings are “23hfd23”, “423131sdd”, etc.

So it converts the given string into double and return true if the given string is numeric otherwise return false.

Algorithm

  • Step 1 − Create a function

  • Step 2 − Return true if the given string is numeric. Otherwise return false.

  • Step 3 − Create a string

  • Step 4 − Pass the string into the function and store the result in a new variable.

  • Step 5 − Print the output.

Example

In the following example, we have three different strings, out of which we are going to print whether any of the three strings are numerical.

import Foundation
import Glibc

// Function to check if the given number is numeric
func checkNumeric(S: String) -> Bool {
   return Double(S) != nil
}

// Test String 1
let str1 = "1233"
let res1 = checkNumeric(S:str1)
print("Is \(str1) is numeric string?:", res1)

// Test String 2
let str2 = "12st45ri54ng"
let res2 = checkNumeric(S:str2)
print("Is \(str2) is numeric string?:", res2)

// Test String 3
let str3 = "Mycar"
let res3 = checkNumeric(S:str3)
print("Is \(str3) is numeric string?:", res3)

Output

Is 1233 is numeric string?: true
Is 12st45ri54ng is numeric string?: false
Is Mycar is numeric string?: false

Conclusion

So this is how we can check whether the string is numeric using double() initializer of Swift. we create a function to check if the given string is a valid numeric string or not. So in this function we use Double() initializer to convert the given string into double and return true if the given string is numeric. Otherwise return false if the given string is not numeric.

Updated on: 19-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements