Skip to content

Instantly share code, notes, and snippets.

@jimbrayrcp
Last active May 6, 2020 16:07
Show Gist options
  • Save jimbrayrcp/ecdbfdf96842803ab109d1a5ed33ba06 to your computer and use it in GitHub Desktop.
Save jimbrayrcp/ecdbfdf96842803ab109d1a5ed33ba06 to your computer and use it in GitHub Desktop.
Swift 5: iOS: 13.1 Converts String to Integer, Double, Float, Bool Use : let myString = "51.55522222222" print(myString.toInteger() ?? "") print(myString.toDouble() ?? "") print(myString.toFloat() ?? "") print(myString.toBool() ?? "")
import Foundation
// ...
extension String {
// Converts String to Integer
public func toInteger() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
}
//Converts String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
//Converts String to Bool
public func toBool() -> Bool? {
return (self as NSString).boolValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment