Swift Combine: Map Keypath

KD Knowledge Diet
2 min readOct 29, 2022

--

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.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by 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!

No responses yet

Write a response