How to masking the last number in Swift?

允我心安 提交于 2019-12-02 04:05:25

Use a prefix instead of a suffix

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

You could also create a function instead for parameterizing the number of digits and direction (or even the mask character)

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!