Last active
August 10, 2017 20:11
-
-
Save micheltlutz/4f28be1a2cbb2e017711d3b41b1f72b6 to your computer and use it in GitHub Desktop.
Swift 3 String Extensions
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
import Foundation | |
extension String | |
{ | |
/** | |
* Return formated currency string by locale with or not round | |
* @see https://developer.apple.com/documentation/foundation/numberformatter, https://developer.apple.com/documentation/foundation/numberformatter.style | |
* @return String if problem on format return string "" | |
*/ | |
func toCurrency(localeItendifier: String = "pt_BR", withRound: Bool = false) -> String{ | |
let numberFormatter: NumberFormatter = { | |
let formater = NumberFormatter() | |
formater.numberStyle = .currency | |
formater.locale = Locale(identifier: localeItendifier) | |
formater.alwaysShowsDecimalSeparator = true | |
formater.minimumFractionDigits = 2 | |
formater.maximumFractionDigits = 2 | |
return formater | |
}() | |
let valToFloat = Float(self)! | |
var val: NSNumber | |
if(withRound){ | |
val = NSNumber(value: round(valToFloat)) | |
} else { | |
val = NSNumber(value: valToFloat) | |
} | |
if let formmatedVal = numberFormatter.string(from: val){ | |
return formmatedVal | |
} | |
return "" | |
} | |
/** | |
* Shortcut replacingOccurrences | |
* @return String - string replaced | |
*/ | |
func replace(this: String, to: String) -> String | |
{ | |
return self.replacingOccurrences(of: this, with: to) | |
} | |
/** | |
* Remove all another char did not match with characterset decimalDigits | |
* @see https://developer.apple.com/documentation/foundation/characterset | |
* @return String - String decimals | |
*/ | |
func getDecimals() -> String | |
{ | |
return components(separatedBy: CharacterSet.decimalDigits.inverted).joined() | |
} | |
/** | |
* Verify if char is a utf8 backspace, util for testin keyboard keypress | |
* @see https://developer.apple.com/documentation/swift/string/1641523-init | |
* @see https://developer.apple.com/documentation/kernel/1579329-strcmp | |
* @return Bool - if a backspace char return true else false | |
*/ | |
func isBackSpace() -> Bool | |
{ | |
let char = self.cString(using: String.Encoding.utf8)! | |
let isBackSpace = strcmp(char, "\\b") | |
if(isBackSpace == -92){ return true } | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
var compras = "R$1000.99"
var comprasnumero = "12300.92"
print(comprasnumero.toCurrency())
print(comprasnumero.toCurrency(localeItendifier: "pt_BR", withRound: true))
print(compras.replace(this: "R$", to: ""))
print(compras.getDecimals())
print(compras.isBackSpace())