Commonly used functions

  • Remove the leading and trailing Spaces
  • Remove leading and trailing Spaces and line feeds
  • Remove all Spaces
  • Gets the width of the string displayed in the label
  • Gets the height of the string displayed in the label
  • Generating random strings

validation

  • Email address verification
  • Phone verification
  • Whether Chinese characters are included

Time correlation

  • Get the current timestamp in seconds
  • Get the current timestamp (ms)
  • Get the current time
  • Timestamp to format time (seconds)
  • Timestamp to format time (ms)

code

import Foundation
import UIKit

// MARK: - Common functions
extension String {
    
    /// remove the leading and trailing Spaces
    var removeHeadAndTailSpace: String {
        return self.trimmingCharacters(in: .whitespaces)
    }
    
    /// remove leading and trailing Spaces and newlines
    var removeHeadAndTailSpaceNewLine: String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
    
    /// remove all whitespace
    var removeAllSpace: String {
        
        do {
            let regularExpression = try NSRegularExpression(pattern: "\ \s*", options: .caseInsensitive)
            return regularExpression.stringByReplacingMatches(in: self, options: .withTransparentBounds, range: NSRange(location: 0, length: self.count), withTemplate: "")}catch _ {
            return self.replacingOccurrences(of: "", with: "", options: .literal, range: nil).replacingOccurrences(of: "", with: "", options: .literal, range: nil)}}/// Gets the width of the string displayed in the label
    /// - Parameters:
    /// -font
    /// -height: label height
    /// - Returns: displays wide
    func getWidth(font: UIFont.height: CGFloat) -> CGFloat {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat(MAXFLOAT), height: height))
        label.text = self
        label.font = font
        label.textAlignment = .left
        label.sizeToFit()
        return label.width
    }
    
    /// Gets the height of the string displayed in the label
    /// - Parameters:
    /// -font
    /// -width: label width
    /// - Returns: Displays high
    func getHeight(font: UIFont.width: CGFloat) -> CGFloat {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT)))
        label.text = self
        label.font = font
        label.textAlignment = .left
        label.numberOfLines = 0
        label.sizeToFit()
        return label.height
    }
    
// /// MD5 encryption
// var md5:String {
// let utf8 = cString(using: .utf8)
// var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
// CC_MD5(utf8, CC_LONG(utf8! .count - 1), &digest)
// return digest.reduce("") { $0 + String(format:"%02X", $1) }
/ /}
    
    /// Generate random strings
    ///
    /// - Parameters:
    /// -count: generates the length of the string
    /// -isletter: false= uppercase letters and digits, true= uppercase letters, false by default
    /// - Returns: String
    static func random(_ count: Int._ isLetter: Bool = false) -> String {
        
        var ch: [CChar] = Array(repeating: 0, count: count)
        for index in 0..<count {
            
            var num = isLetter ? arc4random_uniform(58)+65:arc4random_uniform(75)+48
            if num>57 && num<65 && isLetter= =false { num = num%57+48 }
            else if num>90 && num<97 { num = num%90+65 }
            
            ch[index] = CChar(num)
        }
        
        return String(cString: ch)
    }
}



// MARK: - Verify
extension String {
    
    /// Email authentication
    func isValidateEmail(a) -> Bool {
        let emailRegex = "^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\ \.). +[a-z]{2,}$"
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with:self)}/// Verify by phone
    func isTelPhone(a) -> Bool {
        
        let telRegex1 = "^ [0-9] {10} $";
        let telRegex2 = "^ [0-9] {3} - [0-9] {3} - [0-9] {4} $";
        let telRegex3 = "^\ \([0-9] {3}\ \) [0-9] {3} - [0-9] {4} $";
        let telRegex4 = "^\ \([0-9] {3}\ \) [0-9] {7} $";
        let telRegex5 = "^ [0-9] {3} - [0-9] {4} $";
        let telRegex6 = "^ [0-9] {3}\ \. [0-9] {3}\ \. [0-9] {4} $";
        
        let telTest1 = NSPredicate(format: "SELF MATCHES %@", telRegex1)
        let telTest2 = NSPredicate(format: "SELF MATCHES %@", telRegex2)
        let telTest3 = NSPredicate(format: "SELF MATCHES %@", telRegex3)
        let telTest4 = NSPredicate(format: "SELF MATCHES %@", telRegex4)
        let telTest5 = NSPredicate(format: "SELF MATCHES %@", telRegex5)
        let telTest6 = NSPredicate(format: "SELF MATCHES %@", telRegex6)
        return telTest1.evaluate(with:self)||telTest2.evaluate(with:self)||telTest3.evaluate(with:self)||telTest4.evaluate(with:self)||telTest5.evaluate(with:self)||telTest6.evaluate(with:self)}/// Whether to include Chinese characters
    func isIncludeChineseIn(a) -> Bool {
        
        for (_, value) in self.enumerated() {

            if ("\u{4E00}" < = value  && value < = "\u{9FA5}") {
                return true}}return false}}// MARK: - Time dependent
extension String {
    
    // get the current timestamp (in seconds)
    static func getNowTimeStamp(a) -> String {
        // Get the current time
        let now = Date(a)// Timestamp of the current time
        let timeInterval:TimeInterval = now.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return "\(timeStamp)"
    }
    
    // get the current timestamp (ms)
    static func getNowTimeMilliStamp(a) -> String {
        // Get the current time
        let now = Date(a)// Timestamp of the current time
        let timeInterval: TimeInterval = now.timeIntervalSince1970
        let millisecond = CLongLong(round(timeInterval*1000))
        return "\(millisecond)"
    }
    
    /// Get the current time
    /// -parameter dateFormat: time format (e.g. Yyyy-mm-dd HH: MM :ss)
    static func getNowTimeString(dateFormat: String) -> String {
        // Get the current time
        let now = Date(a)// Create a date formatter
        let dformatter = DateFormatter()
        dformatter.dateFormat = dateFormat
        return dformatter.string(from: now)
    }
    
    // time to format (s)
    /// -parameter dateFormat: time format (e.g. Yyyy-mm-dd HH: MM :ss)
    func getTimeString(dateFormat: String) -> String {
        guard let timeStamp = Double(self) else { return "" }
        // Convert to time
        let timeInterval:TimeInterval = TimeInterval(timeStamp)
        let date = Date(timeIntervalSince1970: timeInterval)
        // Create a date formatter
        let dformatter = DateFormatter()
        dformatter.dateFormat = dateFormat
        return dformatter.string(from: date)
        
    }
    
    /// timestamp to format time (ms)
    /// -parameter dateFormat: time format (e.g. Yyyy-mm-dd HH: MM :ss)
    func getMilliTimeString(dateFormat: String) -> String {
        guard let timeStamp = Double(self) else { return "" }
        // Convert to time
        let timeInterval:TimeInterval = TimeInterval(timeStamp/1000)
        let date = Date(timeIntervalSince1970: timeInterval)
        // Create a date formatter
        let dformatter = DateFormatter()
        dformatter.dateFormat = dateFormat
        return dformatter.string(from: date)
        
    }
    
}

Copy the code

Demo: Github