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.

--

--

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!