Search code examples
swiftstringmasking

How to mask a String to show only the last 3 characters?


I just tried to mask String as below, but I didn't find what I want after do some search and research.

string a = "0123456789" masked = "xxxxxxx789"

I modified solutions in this questions http://stackoverflow.com/questions/41224637/masking-first-and-last-name-string-with but it just change the String that doesn't match with the pattern. I have no idea how to change the pattern to match with what I mean.


Solution

  • This does exactly what you want:

    let name = "0123456789"
    let conditionIndex = name.characters.count - 3
    let maskedName = String(name.characters.enumerated().map { (index, element) -> Character in
        return index < conditionIndex ? "x" : element
    })
    print("Masked Name: ", maskedName) // xxxxxxx789
    

    What happens here is that you get an array of the characters of the string using enumerated() method, then map each character to a value based on a condition:

    • If the index of the character is less than condtionIndex we replace the character with an x (the mask).
    • Else, we just leave the character as is.