Ultimate Swift Extensions for String, Date, Optional, and Number
Written on
Welcome back to another discussion on practical extensions in Swift.
Optional Extension:
When dealing with optionals, the following extensions can simplify your code. Instead of repeatedly using the ?? operator throughout your project, you can simply create an extension and utilize the getOptionalValue() function on optional strings.
extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
return self?.isEmpty ?? true}
func getOptionalValue() -> String {
return self ?? ""}
}
You can use getOptionalValue() as follows:
let car: String?
print("Result: (car.getOptionalValue())") // prints an empty string.
car = "BMW"
print("Result: (car.getOptionalValue())") // prints "BMW".
To check if a string is nil or empty, use isNilOrEmpty() as shown below:
let car: String?
print("Result: (car.isNilOrEmpty())") // prints true.
car = "BMW"
print("Result: (car.isNilOrEmpty())") // prints false.
NumberFormatter Extension:
This extension helps retrieve the currency format for the user's locale.
extension NumberFormatter {
func currencyFormatterUSA() -> NumberFormatter {
let locale = Locale(identifier: "en_US")
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
formatter.currencySymbol = locale.currencySymbol
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
formatter.alwaysShowsDecimalSeparator = true
formatter.generatesDecimalNumbers = true
formatter.formatterBehavior = .behavior10_4
formatter.isLenient = true
return formatter
}
}
For example, calling currencyFormatterUSA() will format the currency as US dollars:
let statementBalanceAmount = "3200"
print("Result: (statementBalanceAmount.currencyFormatterUSA())") // prints $3,200.
String Extensions:
To encode special characters for API requests, you can use the following extension.
extension String {
func encodeChars() -> String {
var temp = self
temp = temp.replacingOccurrences(of: "$", with: "%24") // encode other special characters similarly
return temp
}
}
Usage example:
let test = "A$2"
print("Result: (test.encodeChars())") // Result: A%242
To encode a string for server transmission:
func encodedString() -> String {
var temp = ""
if let encodeText = self.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) {
let encodeString = encodeText.encodeChars()
temp = encodeString
}
return temp
}
Usage example:
let testEncode = "This is a"
print("Result: (testEncode.encodedString())") // Result: This%20is%20a
For formatting currency in the US format, use:
func formatCurrencyToUSA() -> String {
guard let value = Double(self) else { return "" }
let currencyFormatter = NumberFormatter.currencyFormatterUSA()
let numberVal = NSNumber(value: value)
return currencyFormatter.string(from: numberVal) ?? ""
}
Example usage:
let amount = "10"
print("Result: (amount.formatCurrencyToUSA())") // Result: $10
To obtain the plain amount without the dollar sign:
func getPlainAmountText() -> String {
var amount = self.replacingOccurrences(of: "$", with: "")
amount = amount.replacingOccurrences(of: ",", with: "")
amount = amount.trimmingCharacters(in: .whitespacesAndNewlines)
return amount
}
Example usage:
let amount = "$10"
print("Result: (amount.getPlainAmountText())") // Result: 10
Attributed HTML Tag:
To render HTML tags in the UI (like in labels or text views), you can use the following method:
func getHTMLAttributedString() -> NSMutableAttributedString {
let encodedData = self.data(using: .utf8)!
var attributedString: NSMutableAttributedString?
do {
attributedString = try NSMutableAttributedString(data: encodedData, options: [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
], documentAttributes: nil)
} catch let error as NSError {
print(error)}
return attributedString ?? NSMutableAttributedString(string: "")
}
Example usage:
let responseString = "<b>Hello</b> <br/> World"
self.someLabel.attributedText = responseString.getHTMLAttributedString()
This will render "Hello" in bold and "World" on a new line.
Remove HTML Tags:
To eliminate HTML tags from a string, use the following extension:
func removeHTMLTags() -> String {
return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)}
Example usage:
let responseString = "<b>Hello</b> <br> World"
print("Result: (responseString.removeHTMLTags())") // Result: Hello World
Date Extension:
Enhance the Date functionality with these useful extensions.
extension Date {
func addDays(howManyDaysOnToday: Int) -> Date? {
return Calendar.current.date(byAdding: .day, value: howManyDaysOnToday, to: self)}
func getMinute(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? .zero}
func getWeekDayName() -> String {
let weekDay = Calendar.current.component(.weekday, from: self)
let weekDayArray: [String] = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
return weekDayArray[weekDay - 1]
}
}
Example usage:
print("Result: (Date().addDays(howManyDaysOnToday: 1))") // Result: Date + 1
Conclusion:
We've explored several valuable extensions that can enhance your coding experience. If you found this information helpful, please give a clap!