0

I have string extension you can see under below but only returns true for Int , I want to return it true, for All , Int and Double values only.

extension String  {
    var isnumberordouble : Bool {
        get{
            return self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
        }
    }
}

How can I fix it ? Any idea ? ty.

Hamish
  • 78,605
  • 19
  • 187
  • 280
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85

1 Answers1

6

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
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • 2
    Checking for Double might be sufficient... A string representing an integer should also be a valid double. – Martin R May 29 '17 at 13:25