Skip to content

Instantly share code, notes, and snippets.

@dan-hill
Created October 25, 2014 05:56
Show Gist options
  • Save dan-hill/9d5f8ec2d5878b2f7838 to your computer and use it in GitHub Desktop.
Save dan-hill/9d5f8ec2d5878b2f7838 to your computer and use it in GitHub Desktop.
Extension to string that adds the toDouble() function with some error checking.
extension String {
func toDouble() -> Double? {
var chars: [Character] = Array(self)
if (chars.filter {$0 == "."}.count > 1) {
return nil
}
var dotIndex: Int? = find(chars, ".")
if dotIndex != nil {
chars.removeAtIndex(dotIndex!)
}
if (String(seq: chars).toInt() == nil) {
return nil
}
return NSNumberFormatter().numberFromString(self)!.doubleValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment