Swift:String+Extension

1. 判断字符串是否是3-15位数字或者邮箱
extension String {
    // 是否是3-15位数字
    func validateMobileNumber() -> Bool {
        let regex = "^\\d{3,15}$" 
        return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self)
    }
    
    // 是否是邮箱
    func validateEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
    }
}
2. 判断字符串是否包含某个字符串
extension String {
    /// 判断是否含有某个字符串
    func contains(find: String) -> Bool {
        return self.range(of: find) != nil
    }

    /// 判断是否含有某个字符串 忽略大小写
    func containsIgnoringCase(find: String) -> Bool {
        return self.range(of: find, options: .caseInsensitive) != nil
    }
}
3. 计算字符串宽度或者高度
// 计算字符串尺寸大小
extension String {
    /// 根据字符串计算高度尺寸,width 默认是最大数
    func size(font: UIFont, width: CGFloat = CGFloat.greatestFiniteMagnitude, paragraphStyle: NSParagraphStyle = NSParagraphStyle.default) -> CGSize {
        var attributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font : font]
        attributes[NSAttributedStringKey.paragraphStyle] = paragraphStyle
        let rect = self.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
                                     options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                     attributes: attributes,
                                     context: nil)
        return rect.size
    }

    /// 根据字符串计算宽度尺寸
    func getSizeWithHeight(font: UIFont, height: CGFloat = CGFloat.greatestFiniteMagnitude, paragraphStyle: NSParagraphStyle = NSParagraphStyle.default) -> CGSize {
        var attributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font : font]
        attributes[NSAttributedStringKey.paragraphStyle] = paragraphStyle
        let rect = self.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: height),
                                     options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                     attributes: attributes,
                                     context: nil)
        return rect.size
    }

}

4. 判断字符串是否有值
extension String {
   /**
   true if self contains characters.
   */
   var isNotEmpty: Bool {
       return !isEmpty
   }
}

你可能感兴趣的:(Swift:String+Extension)