Last active
November 26, 2021 08:50
-
-
Save pablogm/4ad14e100416d6a804aa to your computer and use it in GitHub Desktop.
Swift String extensions: localized strings, html to attributed string, check if valid email, generate random string, ...
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
// | |
// String+Localizable.swift | |
// Swift extensions | |
// | |
import Foundation | |
import UIKit | |
// MARK: Localized | |
extension String { | |
var localized: String { | |
return self.localizedWithComment("") | |
} | |
} | |
extension String { | |
func localizedWithComment(comment:String) -> String { | |
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: comment) | |
} | |
} | |
// MARK: Html to Attbributed | |
extension String { | |
var html2AttStr:NSAttributedString { | |
do { | |
let string = try NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil) | |
return string | |
} | |
catch { | |
print("Error creating attributed string!") | |
} | |
return NSAttributedString(string: self) | |
} | |
} | |
// MARK: Check if an email is valid | |
extension String { | |
func isValidEmail() -> Bool { | |
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" | |
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) | |
return emailTest.evaluateWithObject(self) | |
} | |
} | |
// MARK: Generated random string | |
extension String { | |
static func randomStringWithLength (len : Int) -> NSString { | |
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
let randomString : NSMutableString = NSMutableString(capacity: len) | |
for (var i=0; i < len; i++){ | |
let length = UInt32 (letters.length) | |
let rand = arc4random_uniform(length) | |
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand))) | |
} | |
return randomString | |
} | |
} | |
// MARK: Reset string | |
extension String { | |
mutating func clean() { | |
self = "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment