# Read/modify, yield, and non-escaping closures

**URL:** <https://forums.swift.org/t/read-modify-yield-and-non-escaping-closures/61902>\
**Category:** Discussion\
**Created:** [December 7, 2022, 7:37pm UTC](https://forums.swift.org/t/read-modify-yield-and-non-escaping-closures/61902 "2022-12-07T19:37:09Z")\
**Posts on this page:** 2\
**Page:** 1

<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 7, 2022, 7:37pm UTC](https://forums.swift.org/t/read-modify-yield-and-non-escaping-closures/61902/1 "2022-12-07T19:37:09Z")

</div>

I know `_read` and `_modify` are still experimental features, but I was wondering if it should be possible to `yield` from within a closure so long as it's not escaping. For example, should the following non-compiling code work?

```swift
private let lock = NSLock()
private var _x: Int
var x: Int {
  _read { lock.withLock { yield _x } } // 🛑
  _modify { lock.withLock { yield &_x } } // 🛑
}

```

> 🛑 Cannot find 'yield' in scope

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [December 7, 2022, 8:01pm UTC](https://forums.swift.org/t/read-modify-yield-and-non-escaping-closures/61902/2 "2022-12-07T20:01:05Z")

</div>

We need a way to represent this sort of scoped setup in a way that's compatible with coroutines, but we can't really retrofit the ability to yield from an outer coroutine in the middle of a closure in the current representation. What I'd like to see is for single-yield coroutines to eventually be generalized to the point they can supersede `withClosure` style APIs, so you could write something like:

```swift
@noncopyable struct Guard {}

extension NSLock {
  var guard: Guard {
    read {
      _lock()
      yield Guard()
      _unlock()
    }
  }
}

var x: Int {
  read {
    with lock.guard {
      yield _x
    }
  }
}

```
