美文网首页swiftSwift编程Swift
Swift-NSString常用扩展

Swift-NSString常用扩展

作者: 我在鄱阳湖边 | 来源:发表于2018-07-16 17:29 被阅读1次

    //判断是否是中文

    func isChinese() -> Bool {

        let match = "(^[\u{4e00}-\u{9fa5}]+$)"

        let predicate = NSPredicate(format: "SELF matches %@", match)

        return predicate.evaluate(with: self)

    }

    //判断手机号码格式是否正确

    class func valiMobile(_ mobile: String?) -> Bool {

            // 130-139  150-153,155-159  180-189  145,147  170,171,173,176,177,178

        let phoneRegex = "^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678]))\\d{8}$"

        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)

        return phoneTest.evaluate(with: mobile)

    }

    // 判断是否是数字

    class func validateNumber(_ number: String?) -> Bool {

        var res = true

        let tmpSet = CharacterSet(charactersIn: "0123456789")

        let i: Int = 0

        while i < (number?.count ?? 0) {

            let string = (number as NSString?)?.substring(with: NSRange(location: i, length: 1))

            let range: NSRange? = (string as NSString?)?.rangeOfCharacter(from: tmpSet)

            if Int(range?.length ?? 0) == 0 {

                res = false

                break

            }

            i += 1

        }

        return res

    }

    // 判断是否为中文

    class func isChinese(_ string: String?) -> Bool {

        let c = unichar(string?[string?.index(string?.startIndex, offsetBy: 0)] ?? 0)

        if c >= 0x4e00 && c <= 0x9fff {

            return true

        } else {

            return false

        }

        return true

    }

    //格式化电话号码 136 2222 2222

    class func formatPhoneNumber(_ string: String?) -> String? {

        var str1 = string ?? ""

        str1.insert(contentsOf: " ", at: s.index(s.startIndex, offsetBy: 3))

        str1.insert(contentsOf: " ", at: s.index(s.startIndex, offsetBy: 8))

        return str1

    }

    //是否是一个字符

    class func validateCharacter(_ string: String?) -> Bool {

        let cStr = Int8(string?.utf8CString ?? 0)

        if strlen(cStr) == 1 {

            return true

        }

        return false

    }

    // 判断身份证号是否正确

    func judgeIdentityStringValid(_ identityString: String?) -> Bool {

        if (identityString?.count ?? 0) != 18 {

            return false

        }

            // 正则表达式判断基本 身份证号是否满足格式

        let regex2 = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"

        let identityStringPredicate = NSPredicate(format: "SELF MATCHES %@", regex2)

        //如果通过该验证,说明身份证格式正确,但准确性还需计算

        if !identityStringPredicate.evaluate(with: identityString) {

            return false

        }

            //** 开始进行校验 *//

            //将前17位加权因子保存在数组里

        let idCardWiArray = ["7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"]

            //这是除以11后,可能产生的11位余数、验证码,也保存成数组

        let idCardYArray = ["1", "0", "10", "9", "8", "7", "6", "5", "4", "3", "2"]

            //用来保存前17位各自乖以加权因子后的总和

        var idCardWiSum: Int = 0

        for i in 0..<17 {

            let subStrIndex = Int(truncating: ((identityString as NSString?)?.substring(with: NSRange(location: i, length: 1)) ?? "")) ?? 0

            let idCardWiIndex = Int(truncating: idCardWiArray[i]) ?? 0

            idCardWiSum += subStrIndex * idCardWiIndex

        }

            //计算出校验码所在数组的位置

        let idCardMod: Int = idCardWiSum % 11

            //得到最后一位身份证号码

        let idCardLast = (identityString as NSString?)?.substring(with: NSRange(location: 17, length: 1))

        //如果等于2,则说明校验码是10,身份证号码最后一位应该是X

        if idCardMod == 2 {

            if !(idCardLast == "X") || (idCardLast == "x") {

                return false

            }

        } else {

            //用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码

            if !(idCardLast == idCardYArray[idCardMod]) {

                return false

            }

        }

        return true

    }

    // 时间戳转时间

    convenience init(fromDateString dateStr: String?) {

        let confromTimesp = Date(timeIntervalSince1970: TimeInterval(Int(truncating: dateStr ?? "") ?? 0))

        let formatter = DateFormatter()

        formatter.dateFormat = "YY-MM-dd HH:mm"

        let confromTimespStr = formatter.string(from: confromTimesp)

        return confromTimespStr

    }

    class func getAgeForm(_ age: Int) -> String? {

        let mouthArr = ["0个月", "1个月", "2个月", "3个月", "4个月", "5个月", "6个月", "7个月", "8个月", "9个月", "10个月", "11个月", "12个月"]

        let yearArr = ["0岁", "1岁", "2岁", "3岁", "4岁", "5岁", "6岁", "7岁"]

        let mouthIndex: Int = age % 12

        let yearIndex: Int = age / 12

        let mouth = mouthArr[mouthIndex]

        let year = yearArr[yearIndex]

        var ageText: String

        if age < 12 {

            ageText = "\(mouth)"

        } else if age == 12 {

            ageText = "1岁"

        } else {

            ageText = "\(year)\(mouth)"

        }

        return ageText

    }

    class func cachePathWithfileName(_ filename: String?) -> String? {

        return URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last ?? "").appendingPathComponent("\(filename ?? "").plist").absoluteString

    }

    // 根据订单创建时间获得订单的倒计时数

    class func getRemainTime(with closeTime: String?) -> Int {

        var closeTime = closeTime

        let date = Date()

            // 当前时间

            //    NSDateFormatter *formate = [[NSDateFormatter alloc] init];

            //    formate.dateFormat = @"YYMMddHHmmss";

            //    NSString *formatDate = [formate stringFromDate:date];

        let timeSp = String(format: "%.0f", date.timeIntervalSince1970)

        // 时间差 剩余时间 关闭时间-当前时间

        if (closeTime?.count ?? 0) > 10 {

            closeTime = (closeTime as NSString?)?.substring(with: NSRange(location: 0, length: 10))

        }

        let timeLast = Int(truncating: closeTime ?? "") ?? 0 - Int(truncating: timeSp) ?? 0

        return timeLast

    }

    // 得到当前的时间戳

    class func getCurrentTime() -> String? {

        let formatter = DateFormatter()

        formatter.dateStyle = .medium

        formatter.timeStyle = .short

        formatter.dateFormat = "YYYY-MM-dd HH:mm:ss SSS"

            // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

            //设置时区,这个对于时间的处理有时很重要

        let timeZone = NSTimeZone(name: "Asia/Shanghai")

        if let aZone = timeZone {

            formatter.timeZone = aZone as TimeZone

        }

        let datenow = Date()

            //现在时间,你可以输出来看下是什么格式

        let timeSp = "\(Int(datenow.timeIntervalSince1970) * 1000)"

        return timeSp

    }

    相关文章

      网友评论

      • 莫莫H:建议用markdown 编辑下,看着方便些

      本文标题:Swift-NSString常用扩展

      本文链接:https://www.haomeiwen.com/subject/kmwbpftx.html