As @MartinR said, check if the string can be converted to an Int or a Double:
extension String {
var isnumberordouble: Bool { return Int(self) != nil || Double(self) != nil }
}
print("1".isnumberordouble) // true
print("1.2.3".isnumberordouble) // false
print("1.2".isnumberordouble) // true
@MartinR raises a good point in the comments. Any value that converts to an Int would also convert to a Double, so just checking for conversion to Double is sufficient:
extension String {
var isnumberordouble: Bool { return Double(self) != nil }
}
Handling leading and trailing whitespace
The solution above works, but it isn't very forgiving if your String has leading or trailing whitespace. To handle that use the trimmingCharacters(in:) method of String to remove the whitespace (requires Foundation):
import Foundation
extension String {
var isnumberordouble: Bool { return Double(self.trimmingCharacters(in: .whitespaces)) != nil }
}
print(" 12 ".isnumberordouble) // true