Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5 replacingOccurrences multiple elements

Tags:

swift

let osetx = "01et"

I want to replace "e" with "11" and "t" with "10." What is the syntax to do that by calling the function only once?

let newOsetx = osetx.replacingOccurrences(of: "e", with: "11")

The above only replaces one of the 2 elements, obviously.

THANK YOU pawello2222 for the syntax in the comments.

osetx.replacingOccurrences(of: "e", with: "11").replacingOccurrences(of: "t", with: "10")

like image 911
matthewmodine Avatar asked May 29 '26 12:05

matthewmodine


2 Answers

xTwisteDx’s answer is correct. Just chain your replacingOccurrences calls.

But just a stylistic observation: Frequently, when chaining a bunch of calls like this, we might break it into separate lines, e.g.

let newOsetx = osetx
    .replacingOccurrences(of: "e", with: "11")
    .replacingOccurrences(of: "t", with: "10")

When you're doing a bunch of replacements, that can make it a little more easy to read the code at a glance.


If you are doing more than two or three replacements, you might consider using some looping pattern. For example, you could use an array of tuples representing the search and replace strings:

let replacements = [
    ("e", "11"),
    ("t", "10")
]

Then you can loop through them, performing the replacements:

var newOsetx = osetx

for (searchString, replacement) in replacements {
    newOsetx = newOsetx.replacingOccurrences(of: searchString, with: replacement)
}

Or you can use reduce:

let newOsetx = replacements.reduce(osetx) { string, replacement in
    string.replacingOccurrences(of: replacement.0, with: replacement.1)
}
like image 81
Rob Avatar answered Jun 01 '26 04:06

Rob


You can chain your method calls. replacingOccurrences is a string method that does something to the string, but it returns a string. As a result, you can chain the result of the first and then do the same again. In fact you can do this an indeterminate amount of times, however there are better ways to do it.

newOsetx = osetx.replacingOccurrences(of: "e", with: "ll").replacingOccurrences(of: "t", with: "10")

Another option would be to do it like this.

newOsetx = osetx.replacingOccurrences(of: "e", with: "ll")
let finalOsetX = newOsetx.replacingOccurrences(of: "t", with: "10")

In general have a look at the returned type of a method, it shows up in the drop down window. That returned type will have methods that it can be used with as well.

like image 29
xTwisteDx Avatar answered Jun 01 '26 02:06

xTwisteDx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!