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