Search code examples
swifttextfieldmasking

How to masking textfield in Swift 4?


I want masking email in textfield.text, but I only get the value in the middle. I want to get the value from the middle to @ gmail.com like example below.

ex:

  1. let var = [email protected]

output = ****[email protected]

  1. let var = [email protected]

output = ****[email protected]

    let email = "[email protected]"

    let components = email.components(separatedBy: "@")

    let result = hideMidChars(components.first!) + "@" + components.last!

    print(result)

output I get: ****5****@gmail.com

my expectations: ****[email protected]


Solution

  • func hide(email: String) -> String {
    
        let parts = email.split(separator: "@")
        if parts.count < 2 {
            return email
        }
        let name = parts[0]
        let appendix = parts[1]
        let lenght = name.count
        if lenght == 1 {
            return "*@\(appendix)"
        }
        let semiLenght = lenght / 2
    
        var suffixSemiLenght = semiLenght
        if (lenght % 2 == 1) {
            suffixSemiLenght += 1
        }
    
        let prefix = String(repeating: "*", count: semiLenght)
        let lastPart = String(name.suffix(suffixSemiLenght))
    
        let result = "\(prefix)\(lastPart)@\(appendix)"
        return result
    }
    let email = "[email protected]"
    let result = hide(email: email)
    print(result)