#Is not empty
#Is blank
#Localized
#Replace at with
#Attributed
#Height for width and font
#Trimmed
#Numeric
#isNumeric
#Capitalize first letter
#Random letter
#Random character
#Take
#Removed last
#Words array
#Size
#Is valid url
Sometimes it's way more readable.
var isNotEmpty: Bool {
return !isEmpty
}Checks if trimmed string is empty.
var isBlank: Bool {
return trimmed().isEmpty
}Example: title = "your_screen_title".localized. You should have a value under this key in your Localizable.strings file("your_screen_title" = "Swift extensions";)
var localized: String {
return NSLocalizedString(self, comment: "")
}
func localized(_ args: CVarArg...) -> String {
return String(format: self.localized, locale: Locale.current, arguments: args)
}Replaces character at index.
func replace(at index: Int, with newChar: Character) -> String {
var chars = Array(self)
chars[index] = newChar
let modifiedString = String(chars)
return modifiedString
}To easily set attributes.
func attributed(size: CGFloat = 17.0,
letterSpacing: CGFloat = 1.6,
weight: UIFont.Weight = .regular,
lineSpacing: CGFloat? = nil) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self, attributes: [
.font: UIFont.systemFont(ofSize: size, weight: weight),
.kern: letterSpacing
])
if let lineSpacing = lineSpacing {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.alignment = .center
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
}
return attributedString
}Counts height depending on width and font.
func height(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect,
options: .usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font: font],
context: nil)
return ceil(boundingBox.height)
}Returns a new string made by removing from both ends of the String characters contained in a given character set.
func trimmed(_ charSet: CharacterSet = CharacterSet.whitespacesAndNewlines) -> String {
return self.trimmingCharacters(in: charSet)
}Remove all non-numeric characters from a string
var numeric: String {
return self.components(separatedBy: CharacterSet(charactersIn: ".0123456789").inverted).joined(separator: "")
}Check if string contains only numbers
var isNumeric: Bool {
guard !self.isEmpty else { return false }
let nums: Set<Character> = [".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
return Set(self).isSubset(of: nums)
}Returns the same text, capitalizing the first letter.
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}Returns random letter.
static var randomLetter: String {
let characters : String = "abcdefghijklmnopqrstuvwxyz"
let randomIndex = characters.index(characters.startIndex, offsetBy: Int(arc4random_uniform(UInt32(characters.count))))
return String(characters[randomIndex])
}Returns random character. Might be uppercased.
static func randomCharacter(uppercased: Bool = false) -> Character {
let characters: String = uppercased ? "abcdefghijklmnopqrstuvwxyz".uppercased() : "abcdefghijklmnopqrstuvwxyz"
let randomIndex = characters.index(characters.startIndex, offsetBy: Int(arc4random_uniform(UInt32(characters.count))))
return characters[randomIndex]
}Takes elements from the beginning. "0123456789".take(3) | Result: 012
func take(_ offset: Int) -> String {
let offset = self.index(self.startIndex, offsetBy: min(self.count, offset))
return String(self[..<offset])
}"0123456789".removedLast(3) | Result: 0123456
func removedLast(_ offset: Int) -> String {
guard let offset = self.index(endIndex, offsetBy: -offset, limitedBy: startIndex) else { return "" }
return String(self[..<offset])
}Creates array of words separated by space.
var wordsArray: [String] {
return self.components(separatedBy: " ").filter { !$0.isEmpty }
}Returns the bounding box size the receiver occupies when drawn with the given attributes.
func size(_ font: UIFont) -> CGSize {
let fontAttributes = [NSAttributedString.Key.font: font]
return self.size(withAttributes: fontAttributes)
}Checks if valid url.
var isValidUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme == "http" || url.scheme == "https"
}Checks if valid email.
var isValidEmail: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}