Home > other >  How can i mask the first and last characters in Swift?
How can i mask the first and last characters in Swift?

Time:04-23

I have an extension to mask the first and last characters. When I try to mask last characters it works but if I try to mask the first characters it doesn't mask as I want to.

For example;

extension String {
    func maskedChar(_ charCount: Int, lastCharacters: Bool = true) -> String {
        if self.count <= charCount {
            return self
        }
        let mask = String(repeating: "*", count: charCount)
        return lastCharacters ? self.prefix(self.count - charCount)   mask : self.suffix(self.count - charCount)   mask
    }
}

let sample = "123456"
print(sample.maskedChar(3))
print(sample.maskedChar(3, lastCharacters: false))

// 123***
// 456***

What I want to see is basically ***456.

And also, is there any way to shorten the code? The return line is too long to see it.

CodePudding user response:

Pretty simple, really. You just need to reverse the order of the characters from the string and the mask in the "not lastCharacters" case:

extension String {
    func maskedChar(_ charCount: Int, lastCharacters: Bool = true) -> String {
        if self.count < charCount {
            return String(repeating: "*", count: self.count)
        }
        let mask = String(repeating: "*", count: charCount)
        if lastCharacters {
            return self.prefix(self.count - charCount)   mask
        } else {
            return mask   self.suffix(self.count - charCount)
        }
    }
}

Note that I also changed the if clause at the beginning. It seems to me you should ALWAYS mask the data, even if the source string is too short.

CodePudding user response:

I would use dropFirst/dropLast together with the mask you create

extension String {
    func maskedChar(_ charCount: Int, lastCharacters: Bool = true) -> String {
        if self.count <= charCount { return self }

        let mask = String(repeating: "*", count: charCount)
        return lastCharacters ? self.dropLast(charCount)   mask : mask   self.dropFirst(charCount)
    }
}
  • Related