How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.
NSS
The easiest and most reliable way is trying to cast as Double
, if the result is nil
- it can't be formed into a legit number.
let strings = ["test", "123", "123.2", "-123", "123-3", "123..22", ".02"]
let validNumbers = strings.compactMap(Double.init)
print(validNumbers)
// prints [123.0, 123.2, -123.0, 0.02]
More info in the documentation: https://developer.apple.com/documentation/swift/double/2926277-init