Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.
Using Character.isDigit(char ch). If the character is a digit then return true, else return false.
The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.
I find this solution, in Swift 3, to be cleaner
import Foundation
CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourString))
You just need to check whether the Set
of the characters of your String
is subset of the Set
containing the characters from 0 to 9.
extension String {
var isNumeric: Bool {
guard self.characters.count > 0 else { return false }
let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
return Set(self.characters).isSubset(of: nums)
}
}
"".isNumeric // false
"No numbers here".isNumeric // false
"123".isNumeric // true
"Hello world 123".isNumeric // false
Expanding on the fantastic work from Luca above, here is the answer given written by way of Swift 5.
extension String {
var isNumeric: Bool {
guard self.count > 0 else { return false }
let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
return Set(self).isSubset(of: nums)
}
}
We have to check whether every character of the string is a digit or not and string must not be empty.
extension String {
var isNumeric: Bool {
return !(self.isEmpty) && self.allSatisfy { $0.isNumber }
}
}
allSatisfy(_ predicate: (Character) throws -> Bool) rethrows -> Bool is a method which returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
For reference: https://developer.apple.com/documentation/swift/array/2994715-allsatisfy
Example:
let string = "123" string.isNumeric ---- returns true
let string_One = "1@3" string_One.isNumeric ---- returns false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With