Skip to content

Instantly share code, notes, and snippets.

@kumo
Last active August 29, 2015 14:17
Show Gist options
  • Save kumo/7955915e77a3769a0dda to your computer and use it in GitHub Desktop.
Save kumo/7955915e77a3769a0dda to your computer and use it in GitHub Desktop.
extension String {
/** If the string represents an double that fits into an Double, returns the corresponding double. This accepts strings that match the regular expression "[+-]?(?:\d*[\.,])?\d+" only. **/
func toDouble() -> Double? {
let pattern = "^[+-]?(?:\\d*[\\.,])?\\d+$"
var error: NSError? = nil
if let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: &error) {
let numberOfMatches = regex.numberOfMatchesInString(self, options: nil, range: NSMakeRange(0, countElements(self)))
if numberOfMatches != 1 {
return nil
}
let dottedString = self.stringByReplacingOccurrencesOfString(",", withString: ".", options: NSStringCompareOptions.LiteralSearch, range: nil)
return strtod(dottedString, nil)
}
return 0.0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment