Skip to content

Instantly share code, notes, and snippets.

@DigitalLeaves
Last active December 19, 2016 15:03
Show Gist options
  • Save DigitalLeaves/7f42d6a0c1fc49cdb7151ee68f5f0a8d to your computer and use it in GitHub Desktop.
Save DigitalLeaves/7f42d6a0c1fc49cdb7151ee68f5f0a8d to your computer and use it in GitHub Desktop.
//
// 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