Home > Enterprise >  How to replace last 3 characters in Swift?
How to replace last 3 characters in Swift?

Time:09-17

I'm trying to replace last three characters with "*", but I do not think I'm doing it okay. I'll share my code below :

//This is the string and is looking like this : 07123456789
var phoneNumber = viewModel.securityAndLoginAssetsData?.userProfile.phones.phoneLogin 
let endIndex = phoneNumber!.index(phoneNumber!.startIndex, offsetBy: -3)
var finalPhoneNumber = phoneNumber!.replaceSubrange(...endIndex, with: "*")

This is how I'm trying to display it, but I got this error : "Type '()' cannot conform to 'StringProtocol'"

 Text(finalPhoneNumber)

What can I do in this case, thanks :)

CodePudding user response:

Try and avoid indices and force unwrapping:

extension String {
    func replacing(last n: Int, with s: String) -> String {
        let replacement = String(repeating: s, count: min(count, n))
        return dropLast(n)   replacement
    }
}

"123456".replacing(last: 3, with: "*") // 123***

CodePudding user response:

The error is pretty self explanatory. finalPhoneNumber is not a String it is a method. This happens because replaceSubrange doesn’t return anything. It is a mutating method. What you need is to pass phoneNumber instead. Note that you have some other issues in your code like unwrapping phoneNumber and offset should be from endIndex. I would also pass starIndex as the limitedBy parameter or use formIndex to mutate endIndex var which doesnt return an optional and won't pass beyond startIndex when offsetting. Something like:

if var phoneNumber = viewModel.securityAndLoginAssetsData?.userProfile.phones.phoneLogin {
    var endIndex = phoneNumber.endIndex
    phoneNumber.formIndex(&endIndex, offsetBy: -3, limitedBy: phoneNumber.startIndex)
    phoneNumber.replaceSubrange(endIndex..., with: repeatElement("*", count: min(3, phoneNumber.count)))
}
  • Related