Useful Extensions: Swift
2 min readMar 2, 2023
- To check whether a phone number is correct or not.
var isValidIndianTenDigitNumberWithoutCountryCode: Bool {
get{
let trimmedString = self.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: "(", with: "")
.replacingOccurrences(of: ")", with: "")
return trimmedString.count == 10
}
}
2. To trim any extra white spaces in a string.
func trim() -> Self{
self.trimmingCharacters(in: .whitespaces)
}
3. To check whether a string is blank or not, after removing all the white spaces.
func isBlank() -> Bool {
self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
4. To calculate age.
extension String {
func calculateAge() -> String {
let formatter = DateFormatter()
formatter.dateFormat = “MM /DD/YYYY"
let yourDate = formatter.date(from: self)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .indian)
let now = Date()
return "\(calendar.components(.year, from: yourDate!, to: now, options: []).year!)"
}
}
5. To get localized variable.
var localized: String{
let appLanguage = LocalisationManager.shared.getPreferredLanguage()
guard let bundlePath = Bundle.main.path(forResource: appLanguage.rawValue, ofType: "lproj"), let bundle = Bundle(path: bundlePath) else {
return NSLocalizedString(self, value: self, comment: "")
}
return NSLocalizedString(self, bundle: bundle, value: self, comment: "Supporting Localization in powerplay app")
}
6. Replacing occurrences of one string with another.
extension String {
func replacingOccurrences(of search: String, with replacement: String, count maxReplacements: Int) -> String {
var count = 0
var returnValue = self
while let range = returnValue.range(of: search) {
returnValue = returnValue.replacingCharacters(in: range, with: replacement)
count += 1
if count == maxReplacements {
return returnValue
}
}
return returnValue
}
}
7. Int ⇾ Double and Double ⇾ Int
extension Int {
func toDouble() -> Double {
Double(self)
}
}
extension Double {
func toInt() -> Int {
Int(self)
}
}
8. To make iPhone vibrate at certain places
import AudioToolbox
extension UIDevice {
static func vibrate() {
AudioServicesPlaySystemSound(1519)
}
}
// usage
UIDevice.vibrate()
9. To check if string contains only digits/alphabets or not.
extension String {
var containsOnlyDigits: Bool {
let notDigits = NSCharacterSet.decimalDigits.inverted
return rangeOfCharacter(from: notDigits, options: String.CompareOptions.literal, range: nil) == nil
}
}
extension String {
var isAlphanumeric: Bool {
!isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
}
10. To get app version from Info.plist
extension Bundle {
var appVersion: String? {
self.infoDictionary?["CFBundleShortVersionString"] as? String
}
static var mainAppVersion: String? {
Bundle.main.appVersion
}
}
// usage
let appVersion = Bundle.mainAppVersion
11. Shake a view
extension UIView {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-10.0, 10.0, -7.0, 7.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}