Home > Software engineering >  How do I skip over a decimal separator in a string?
How do I skip over a decimal separator in a string?

Time:09-17

I'm getting a warning that scanDecimal() was deprecated in iOS 13.0 but I can't find anything that suggests what should be used instead.

In this function, scanner.scanDecimal(nil) is used to simply scan past an NSDecimal representation by returning true.

I've looked through Apple's (cough) documentation and there's no alternative that I can see there. Does anyone know the new way of doing this?

extension String {
  // Returns true if the string represents a proper numeric value.
  // This method uses the device's current locale setting to determine
  // which decimal separator it will accept.

  func isNumeric() -> Bool {
    let scanner = Scanner(string: self)
    
    // A newly-created scanner has no locale by default.
    // We'll set our scanner's locale to the user's locale
    // so that it recognizes the decimal separator that
    // the user expects (for example, in North America,
    // "." is the decimal separator, while in many parts
    // of Europe, "," is used).

    scanner.locale = Locale.current
    
    return scanner.scanDecimal(nil) && scanner.isAtEnd
   }
}

CodePudding user response:

There's a non-deprecated scanDecimal method that doesn't take a parameter and returns a Decimal? instead of a Bool. You can use the return value of this method to determine if the scan was successful or not. If the return value is nil, the scanner failed to scan a Decimal. If not nil, the scan was successful.

return scanner.scanDecimal() != nil && scanner.isAtEnd
  • Related