Swift Combine: replaceNil(), one of useful transformation operator

Let’s take a look at another transformation useful operator replaceNil.

What is replaceNil

It’s pretty obvious in its name replaceNil().

Basically, if you have some sort of an element which is nil, you can replace it with something else.

So, let’s go ahead and take a look at a very simple example.


["A", "B", nil, "D"]

I prepared for an array which contains nil.

Now, I want to replace nil with something else.

Maybe not available, star or missing alphabet.

["A", "B", nil, "D"]
.replaceNil(with: "C")
.sink {
print($0) //Optional(A), Optional(B), Optional(C), Optional(D)

As you can see, nil is replaced with “C”.

But you must know that the returned value is not string. It comes with Optional.

This is what replaceNil actually does.


  • replaceNil() is Transformation Operator.
  • It replaces nil.
  • It returns Optional.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!