Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to masking the last number in Swift?

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•••••

like image 1000
edo oktarifa Avatar asked Nov 21 '25 14:11

edo oktarifa


1 Answers

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
like image 100
Alladinian Avatar answered Nov 24 '25 07:11

Alladinian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!