Swifterswift: StringExtensions - isNumeric - incorrect behavior

Created on 8 Feb 2018  路  12Comments  路  Source: SwifterSwift/SwifterSwift

What did you do?

po "1-2".isNumeric
true

/// SwifterSwift: Check if string contains only numbers.
///
///     "123".isNumeric -> true
///     "abc".isNumeric -> false
///

What did you expect to happen?

Should be false

What happened instead?

Returned true

SwifterSwift Environment

  • SwifterSwift version: 4.1
  • Xcode version: 9.2
  • macOS version running Xcode: High Sierra
  • Swift version: 4
  • Platform(s) running SwifterSwift: iOS
source

All 12 comments

@seifeet totally agree. We should consider special characters and not just letters. Care to make a PR fixing this?

Some might consider this as a testable result. in this case, 1-2 could equal -1, which is numeric.

@wdcurry yes but "1*[email protected]".isNumeric will also return true

@wdcurry You brought to my attention that we need to watch for signed numbers. 馃憣

@SD10 yes I will create a PR fixing this!

@SD10 @wdcurry would it make sense to have 2 separate functions?

isDigits - checks whether the String contains only digit characters.
isNumeric - checks whether the String a valid Swift number.

implementation of isNumeric can be as simple as that: Double("1.2") != nil

so long as the naming is harmonious with the rest of the library for this sort of logic, sounds great.

Hey guys :) @SD10 @seifeet @wdcurry
I was curious about that and decided to try a regex-based approach for a fix, it took a while trying to find a simple one and finally I came up with "(^-?[\d]+$)|(-?[\d]+[.,]{1}[\d]+$)"
The implementation looks like:

public var isNumeric: Bool {
    return range(of: "(^-?[\\d]+$)|(-?[\\d]+[.,]{1}[\\d]+$)",
                     options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil
}

Is a option aproach to implement this fix :)
@seifeet Your Double("1.2") != nilsuggestion is way more simple, but maybe you want to consider this approach on your PR :))

I'm a pragmatic guy, I don't mind a simple cast 馃槄 I don't know which is more performant

@SD10 I also don't know which one is more performant 馃槀 but I love regex since the day I first saw it, so my opinion on that is totally 100% biased 馃槀 馃槄

@LucianoPAlmeida @SD10 I also like Regex solution but it seems like Double solution is more performant on average.
I created a simple playground to test it:
https://gist.github.com/seifeet/f860e67e41e0b90b8397096b54bb3823

Fixed by #396

Was this page helpful?
0 / 5 - 0 ratings

Related issues

LucianoPAlmeida picture LucianoPAlmeida  路  4Comments

fanglinwei picture fanglinwei  路  3Comments

omaralbeik picture omaralbeik  路  3Comments

omaralbeik picture omaralbeik  路  5Comments

pawurb picture pawurb  路  3Comments