# Creating lenses with Swift macros (usecase for arbitrary names at the global scope)

**URL:** <https://forums.swift.org/t/creating-lenses-with-swift-macros-usecase-for-arbitrary-names-at-the-global-scope/68920>\
**Category:** Pitches\
**Tags:** macros\
**Created:** [December 11, 2023, 2:28am UTC](https://forums.swift.org/t/creating-lenses-with-swift-macros-usecase-for-arbitrary-names-at-the-global-scope/68920 "2023-12-11T02:28:22Z")\
**Posts on this page:** 1\
**Showing post:** 44

<div class="post-metadata">

**Author:** ![stephencelis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/stephencelis/32/2675_2.png) [@stephencelis](https://forums.swift.org/u/stephencelis)\
**Post date:** [December 12, 2023, 6:58pm UTC](https://forums.swift.org/t/creating-lenses-with-swift-macros-usecase-for-arbitrary-names-at-the-global-scope/68920/44 "2023-12-12T18:58:34Z")

</div>

> [@Tylerwbrown](#):
>
> I'd say describing these types of functions, `(T) -> T` is much more clear with optics, even without operators, and it's universally shorter. This can be helpful even when using functions from the Swift standard library:
> 
> ```swift
> users.map {
> var user = $0
> user.name = "new name"
> return user
> }
> 
> ```
> 
> vs
> 
> ```swift
> users.map(\User.Lens.name.set("new name"))
> 
> ```

I think the more idiomatic approach is @ExFalsoQuodlibet's `modifyEach` operator above, which was pitched many years ago by the author of the Functional Swift book: [In-place map for MutableCollection](https://forums.swift.org/t/in-place-map-for-mutablecollection/11111)

Your above example would be written in even fewer characters than the lens approach:

```swift
users.modifyEach { $0.name = "new name" }

```

And using the key path subscript traversal mentioned above, you could technically even do something like:

```swift
users[forEach: \.name] = "new name"

```

---

_[View the full topic](https://forums.swift.org/t/creating-lenses-with-swift-macros-usecase-for-arbitrary-names-at-the-global-scope/68920)._
