I am testing some strings such as one, two, three, seven, etc. to see if they are numbers using the code below. It works okay if the string actually is a number but is crashing when the string is not a number as in the word "savings".
The whole point of the method is to find out if the string can be represented as a number so I don't know how to exclude cases where it is not--if indeed that is the problem. I think that's the problem but I guess I could also be missing something as I'm weak on optionals. The string I am running this on that is producing the error is word "savings".
Here is my code:
public extension NSString {
public var asNum: NSNumber {
// let stringValue = String(value: self)
let stringValue = self
let formatter = NumberFormatter()
formatter.isLenient = true
formatter.numberStyle = .spellOut
let num = formatter.number(from: stringValue as String)!///EXCEPTION
return num
}
}
The exception reads:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
In the debugger, I can verify that the stringValue is "savings"
Thanks for any suggestions.