Last active
December 19, 2016 15:03
-
-
Save DigitalLeaves/7f42d6a0c1fc49cdb7151ee68f5f0a8d 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
// | |
// String+NumericValue.swift | |
// Created by Ignacio Nieto Carvajal (https://digitalleaves.com) | |
// | |
import Foundation | |
extension String { | |
func toFailableBool() -> Bool? { | |
switch self.lowercased() { | |
case "true", "t", "yes", "y", "1": | |
return true | |
case "false", "f", "no", "n", "0": | |
return false | |
default: | |
return nil | |
} | |
} | |
func toDouble() -> Double { | |
let numberFormatter = NumberFormatter() | |
numberFormatter.locale = Locale(identifier: "en_US_POSIX") | |
return numberFormatter.number(from: self.replacingOccurrences(of: ",", with: "."))?.doubleValue ?? 0.0 | |
} | |
func toFailableDouble() -> Double? { | |
let numberFormatter = NumberFormatter() | |
numberFormatter.locale = Locale(identifier: "en_US_POSIX") | |
return numberFormatter.number(from: self.replacingOccurrences(of: ",", with: "."))?.doubleValue ?? 0.0 | |
} | |
func toInt() -> Int { | |
return NumberFormatter().number(from: self)?.intValue ?? 0 | |
} | |
func toFailableInt() -> Int? { | |
return NumberFormatter().number(from: self)?.intValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment