Skip to content

Instantly share code, notes, and snippets.

@izhuster
Last active April 10, 2017 18:29
Show Gist options
  • Save izhuster/0572355ea25d5964da73bfd49171e9c4 to your computer and use it in GitHub Desktop.
Save izhuster/0572355ea25d5964da73bfd49171e9c4 to your computer and use it in GitHub Desktop.
/*
I was doing a migration from Swift 2.3 to 3.0.1. When I encountered a String extension that converts a string number,
gives it a format, then returns the formatted string number.
The problem was, I changed to a NumberFormatter instance but the instance method asked me for a NSNumber.
I came with a solution and while it doesn't work for every value, it works for my use.
*/
// Old implementation
extension String {
public func formatNumber() -> String
{
let numerFormatter = NSNumberFormatter()
numerFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
return numerFormatter.stringFromNumber(Int(self)!)!
}
}
// New implementation
// I had two options
// I went with option 2. Because I just can't risk the Int(self) to fail.
// Option 1
extension String {
public func formatNumber() -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let nsnumber = NSNumber(integerLiteral: Int(self)!)
return formatter.string(from: nsnumber) ?? ""
}
}
// Option 2
extension String {
public func formatNumber() -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let number = Int(self) {
let nsnumber = NSNumber(value: number)
return formatter.string(from: nsnumber) ?? ""
} else {
print("Couldn't cast Int(self) at \(#function)")
return ""
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment