Swift Combine: Map Keypath

Combine’s Map Keypath allows you to access individual properties of an object or a structure. It’s very useful if you know it, otherwise, you will end up writing some unnecessary code to manipulate properties of an object or a structure. Good to know!
What is Map Keypath
Just like the map transformation operator, there is also a map keypath operator. It allows you to refer to the individual keys of the particular object that you’re trying to map over.
Example
struct Point {
let x: Int
let y: Int
}let publisher = PassthroughSubject<Point, Never>() publisher.map(\\.x, \\.y)
.sink {
// you have access to x, y
print("x is \\(x) and y is \\(y)")
}publisher.send(Point(x: 2, y: 10))
For this example, you are going to go ahead and create some sort of a structure or an object that will have multiple properties. So, I’m going to go ahead and start with creating a structure and I will call it point. This will represent a point on the screen. And then create a publisher with PassthroughSubject.
With symbol \.
, you can access properties in struct Point
.
Once the publisher fires an event, publisher Map is going to receive data.
Like this, Map keypath will allow you to access the individual values of properties.
Conclusion
- Using map(_ keyPath), you can access object or structure’s properties.