How to masking the last number in Swift?

点点圈 提交于 2019-12-02 07:50:57

问题


How to mask the last string using swift, I have made the code as below. but the code only shows the last number, my expectation is that the code displays the first 5 digits

here my code:

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

var name = "0123456789"

print(name.masked)

I get output: •••••56789

but my expectations: 01234•••••


回答1:


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


来源:https://stackoverflow.com/questions/55279663/how-to-masking-the-last-number-in-swift

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