Last active
January 18, 2021 14:03
-
-
Save mohsinbmwm3/ba0837d9a3695c0167a9a8cf69b520c2 to your computer and use it in GitHub Desktop.
Useful String extensions in swift
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 { | |
var wordCount: Int { | |
let regex = try? NSRegularExpression(pattern: "\\w+") | |
return regex?.numberOfMatches(in: self, range: NSRange(location: 0, length: self.utf16.count)) ?? 0 | |
} | |
func toInt() -> Int? { | |
return Int(self) | |
} | |
func toDouble() -> Double? { | |
return Double(self) | |
} | |
func toFloat() -> Float? { | |
return Float(self) | |
} | |
func isEmailValid() -> Bool { | |
guard !self.isEmpty else { return false } | |
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" | |
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) | |
return emailPred.evaluate(with: self) | |
} | |
func isPhoneNumberValid() -> Bool { | |
guard !self.isEmpty else { return false } | |
let phoneNumberRegex = "^[6-9]\\d{9}$" | |
let phonePred = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex) | |
return phonePred.evaluate(with: self) | |
} | |
func localized() -> String { | |
guard !self.isEmpty else { return self } | |
let result = NSLocalizedString(self, bundle: Bundle.main, comment: "") | |
// If you are using any custom bundle in your app you can pass that in bundle parameter | |
if result != self { | |
return result | |
} | |
return self | |
} | |
func withPrefix(_ prefix: String) -> String { | |
guard !self.hasPrefix(prefix) else { return self } | |
return "\(prefix)\(self)" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment