Last active
August 29, 2015 14:17
-
-
Save kumo/7955915e77a3769a0dda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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