0

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 :)

2 Answers 2

1

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*** 
Sign up to request clarification or add additional context in comments.

2 Comments

Avoid indices? That’s the proper way when dealing with collections
Thanks a lot, is working well. About the force unwrapping, I know is not good practice, but I did it only to keep the errors away to post this question. :)
0

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))) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.