如何屏蔽Swift中的最后一个数字?

时间:2019-03-21 11:40:58

标签: swift string int masking

如何使用swift屏蔽最后一个字符串,我编写了如下代码。但是代码只显示最后一个数字,我希望代码显示前5个数字

这是我的代码:

extension StringProtocol {
    var masked: String {
        return String(repeating: "•", count: Swift.max(0, count-5)) + suffix(5)
    } }

var name = "0123456789"

print(name.masked)

我得到输出:•••••56789

但我的期望是:01234•••••

2 个答案:

答案 0 :(得分:7)

使用前缀而不是后缀

extension StringProtocol {
    var masked: String {
        return prefix(5) + String(repeating: "•", count: Swift.max(0, count-5))
    } 
}

您还可以创建一个函数来参数化数字位数和方向(甚至是掩码字符)

extension StringProtocol {
    func masked(_ n: Int = 5, reversed: Bool = false) -> String {
        let mask = String(repeating: "•", count: Swift.max(0, count-n))
        return reversed ? mask + suffix(n) : prefix(n) + mask
    } 
}

var name = "0123456789"

print(name.masked(5)) 
// 01234•••••

print(name.masked(5, reversed: true)) 
// •••••56789

答案 1 :(得分:0)

如果您想屏蔽电子邮件地址。这是代码

func maskingEmail(email: String) -> String {
    let emailComponents = email.components(separatedBy: "@")
    let emailDomainComponents = emailComponents[1].components(separatedBy: ".")
    let maskedEmailName = String(repeating: "•", count: Swift.max(0, emailComponents[0].count-3)) + emailComponents[0].suffix(3)
    let maskedEmailProvider = String(repeating: "•", count: Swift.max(0, emailDomainComponents[0].count-3)) + emailDomainComponents[0].suffix(3)
    let emailDomain = emailDomainComponents[1]
    return "\(maskedEmailName)@\(maskedEmailProvider).\(emailDomain)"
}

// The Output
print(maskingEmail(email: "pr1vaterelay@gmail.com")) // •••••••••lay@••ail.com
print(maskingEmail(email: "private_relay@bk.ru")) // ••••••••••lay@bk.ru
print(maskingEmail(email: "private.relay@protonmail.com")) // ••••••••••lay@•••••••ail.com