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.
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"]
.publisher
.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.
Conclusion
replaceNil()
is Transformation Operator.- It replaces nil.
- It returns Optional.