# Modify Accessors

**URL:** <https://forums.swift.org/t/modify-accessors/31872>\
**Category:** Pitches\
**Created:** [December 19, 2019, 5:44pm UTC](https://forums.swift.org/t/modify-accessors/31872 "2019-12-19T17:44:52Z")\
**Posts on this page:** 20\
**Page:** 12

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [January 7, 2020, 12:22pm UTC](https://forums.swift.org/t/modify-accessors/31872/225 "2020-01-07T12:22:10Z")

</div>

Changing control flow is always a pitfall, and I don't think `yield` should do so without any hint what is (or might be) happening.  
I don't have any good examples where the accessor should take special care for "failed" yields, so I prefer a simple (user perspective) model where control is always returned to the accessor, no matter what happens during the yield.

When (if) `yield` obtains other uses, we could adopt the `guard let` pattern:

```
modify {
   print("Going to yield")
   yield &someValue
   print("Done - maybe an error happened, but I don't care")
}

...
for value in values {
   guard yield &value else {
       print("Client doesn't want elements anymore, so we stop yielding")
       break
   }
   print("Moving to the next element...")
}
print("Done - maybe an error happened, but I don't care")
...

```

---

<div class="post-metadata">

**Author:** ![glessard](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glessard/32/409_2.png) [@glessard](https://forums.swift.org/u/glessard)\
**Post date:** [January 7, 2020, 1:27pm UTC](https://forums.swift.org/t/modify-accessors/31872/226 "2020-01-07T13:27:31Z")

</div>

> [@Tino](#):
>
> I don't have any good examples where the accessor should take special care for "failed" yields

We do! If an error is thrown by the code that interacts with the yielded memory, then the cleanup must be forbidden from throwing. And that”s what `defer` does.

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [January 7, 2020, 1:51pm UTC](https://forums.swift.org/t/modify-accessors/31872/227 "2020-01-07T13:51:12Z")

</div>

> [@glessard](#):
>
> If an error is thrown by the code that interacts with the yielded memory, then the cleanup must be forbidden from throwing.

Is `modify` itself allowed to throw at all?

---

<div class="post-metadata">

**Author:** ![glessard](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glessard/32/409_2.png) [@glessard](https://forums.swift.org/u/glessard)\
**Post date:** [January 7, 2020, 1:54pm UTC](https://forums.swift.org/t/modify-accessors/31872/228 "2020-01-07T13:54:57Z")

</div>

> [@Tino](#):
>
> Is `modify` itself allowed to throw at all?

Not yet, but throwing accessors are an expected improvement. We shouldn’t design anything that forbids them.

Some 2019 developments:

- [Throwable accessors](https://forums.swift.org/t/throwable-accessors/20509)
- [apple/swift#22749](https://github.com/apple/swift/pull/22749)

---

<div class="post-metadata">

**Author:** ![rex-remind](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rex-remind/32/449_2.png) [@rex-remind](https://forums.swift.org/u/rex-remind)\
**Post date:** [January 7, 2020, 7:43pm UTC](https://forums.swift.org/t/modify-accessors/31872/229 "2020-01-07T19:43:59Z")

</div>

Very excited about this proposal and like the direction, though I lean towards agreeing with brentdax's arguments about control flow so far.

On a separate note, I'm not sure I understand the implications of the following

```swift
struct GetModify {
  var x: String = "👋🏽 Hello"
    
  var property: String {
    get { print("Getting",x); return x }
    modify {
      print("Yielding",x)
      yield &x
      print("Post yield",x)
    }
  }
}

var getModify = GetModify()
let getModify2 = getModify
getModify.property.append(", 🌍!")
// prints:
// Yielding 👋🏽 Hello
// Post yield 👋🏽 Hello, 🌍!
print(getModify2.x)
// What is printed??

```

Does `x` still retain its value semantics therefore it's copied during the modify/yield since it is not uniquely referenced?

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [January 7, 2020, 8:20pm UTC](https://forums.swift.org/t/modify-accessors/31872/230 "2020-01-07T20:20:51Z")

</div>

`x` will still have value semantics. In your example, when you create `getModify2` this will cause the contents of `getModify` to be copied. This causes `getModify.x` to be copied as `getModify2.x`. This will mean the backing buffer of `getModify.x` will no longer be uniquely referenced. So when you modify it, CoW will trigger. The (immaterial, in this case) difference is there will be 2 references to it when it is yielded, rather than the previous 3 when using `get`/`set`. Think of this as similar to what happens when you make a copy of a struct containing a string, then mutate the original with a `mutating func` that modifies `x`.

---

<div class="post-metadata">

**Author:** ![rjchatfield](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rjchatfield/32/915_2.png) [@rjchatfield](https://forums.swift.org/u/rjchatfield)\
**Post date:** [January 22, 2020, 10:59pm UTC](https://forums.swift.org/t/modify-accessors/31872/231 "2020-01-22T22:59:37Z")

</div>

Are there any plans for adding `modify` behaviour to `WritableKeyPath` and the KeyPath subscript? Seems like a nice performance win we all get for free.

---

<div class="post-metadata">

**Author:** ![Braden\_Scothern](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/braden_scothern/32/1580_2.png) [@Braden\_Scothern](https://forums.swift.org/u/Braden_Scothern)\
**Post date:** [February 4, 2020, 12:30am UTC](https://forums.swift.org/t/modify-accessors/31872/232 "2020-02-04T00:30:20Z")

</div>

So I decided to add a modify accessor to the `TupleCollection` @jrose shared on twitter [here](https://twitter.com/UINT_MIN/status/1220764243319906304?s=20) a bit ago.

It didn't end up exactly how I expected so I am wondering would it be reasonable to allow `yield` in a non-escaping closures that are part of coroutines?

What I first tried was this:

```swift
_modify {
    let count = self.endIndex
    withUnsafeMutablePointer(to: &tuple) {
        $0.withMemoryRebound(to: Element.self, capacity: count) {
            yield &$0[position]
        }
    }
}

```

Which resulted in these errors with Xcode 11.3:

```swift
Consecutive statements on a line must be separated by ';'
Use of extraneous '&'
Use of unresolved identifier 'yield'

```

After realizing that `yield` must not be allowed in the scope of those closures I ended up with this:

```swift
_modify {
    let count = self.endIndex
    var movedValue = withUnsafeMutablePointer(to: &tuple) {
        $0.withMemoryRebound(to: Element.self, capacity: count) {
            $0.advanced(by: position).move()
        }
    }
    defer {
        withUnsafeMutablePointer(to: &tuple) {
            $0.withMemoryRebound(to: Element.self, capacity: count) {
                $0.advanced(by: position).initialize(to: movedValue)
            }
        }
    }
    yield &movedValue
}

```

I am fine with the use of `defer` for clean up as proposed in the pitch but think that this could potentially address the need of `defer` in a lot of cases making it a little simpler to use correctly.

---

<div class="post-metadata">

**Author:** ![NobodyNada](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nobodynada/32/788_2.png) [@NobodyNada](https://forums.swift.org/u/NobodyNada)\
**Post date:** [February 4, 2020, 12:45am UTC](https://forums.swift.org/t/modify-accessors/31872/233 "2020-02-04T00:45:02Z")

</div>

A potential problem is that a non-escaping closure may run more than once, or not at all (for example, `map`).

---

<div class="post-metadata">

**Author:** ![Braden\_Scothern](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/braden_scothern/32/1580_2.png) [@Braden\_Scothern](https://forums.swift.org/u/Braden_Scothern)\
**Post date:** [February 4, 2020, 1:41am UTC](https://forums.swift.org/t/modify-accessors/31872/234 "2020-02-04T01:41:32Z")

</div>

True... I didn’t think about that. For generators that would be fine but modify would need to ensure it only happens once.

---

<div class="post-metadata">

**Author:** ![AnotherUser](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anotheruser/32/14927_2.png) [@AnotherUser](https://forums.swift.org/u/AnotherUser)\
**Post date:** [February 19, 2020, 8:00pm UTC](https://forums.swift.org/t/modify-accessors/31872/235 "2020-02-19T20:00:34Z")

</div>

Does it need to yield only once? I don’t quite understand the mechanics behind it, but it seems to me that when a function is trying to modify a value (via its `modify` accessor for example) it may need repeated access to the value’s contents anyway. And assuming `yield` only yields to a single control point (a single caller), this should be fine. Cleanup can happen in `defer`.

That, or I’m misunderstanding the issue. Does the closure return control back to `modify` multiple times? That could be weird...

---

<div class="post-metadata">

**Author:** ![glessard](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glessard/32/409_2.png) [@glessard](https://forums.swift.org/u/glessard)\
**Post date:** [February 19, 2020, 9:29pm UTC](https://forums.swift.org/t/modify-accessors/31872/236 "2020-02-19T21:29:58Z")

</div>

> [@AnotherUser](#):
>
> Does it need to yield only once?

Yes. In the pitch:

> [@ben-cohen](#):
>
> it must be possible for the compiler to guarantee there is exactly one `yield` on every path.

---

<div class="post-metadata">

**Author:** ![AnotherUser](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anotheruser/32/14927_2.png) [@AnotherUser](https://forums.swift.org/u/AnotherUser)\
**Post date:** [February 20, 2020, 2:28am UTC](https://forums.swift.org/t/modify-accessors/31872/237 "2020-02-20T02:28:40Z")

</div>

Okay. I must’ve missed that bit.

I guess that ousts closures, then. Is there any possibility that one might be able to `yield` onto a `DispatchQueue`? Or would plain threadlocking be necessary?

I mean, `DispatchQueue` only ever executes a `sync`ed closure once, correct? Might we add some sort of annotation to hint to the compiler that certain closures will only execute once?

---

<div class="post-metadata">

**Author:** ![Alejandro\_Martinez](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alejandro_martinez/32/821_2.png) [@Alejandro\_Martinez](https://forums.swift.org/u/Alejandro_Martinez)\
**Post date:** [February 21, 2020, 10:06am UTC](https://forums.swift.org/t/modify-accessors/31872/238 "2020-02-21T10:06:39Z")

</div>

I think this is a really interesting pitch and would like to see it move forward.  
About the discussion about yield and defer, I think it's alright as it is.

- I like `yield` not only because it says what it does, but also because is the common name used to refer to _coroutines_.
- I know this is not a topic about async but if we introduce coroutines at the language level I honestly would like to see the same keyword on all features, including async. (imo `async` is too specific)
- The usage of `defer` is quite clear once you understand what's going on. Is not obvious for a newcomer but honestly this feature is a little advanced IMO. You have the normal `set` to start with, where you don't need all this knowledge. That said, if we find an elegant way of improving this I'm all in :)

Also not sure if this has been discussed (sorry, \>200 posts! :) ) by I'm more worried about this than anything else on the pitch:

> [@anandabits](#):
>
> I’m more concerned about the difference between writeback semantics and modify semantics from the perspective of the user. If one needs to guarantee preservation of the original value without a _guarantee_ that the property or subscript has writeback semantics a defensive copy would be necessary. This is a copy that isn’t necessary today, which means that introducing a `modify` accessor to an existing property as an optimization could break existing code using that property in a subtle way.

---

<div class="post-metadata">

**Author:** ![mattrips](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mattrips/32/4079_2.png) [@mattrips](https://forums.swift.org/u/mattrips)\
**Post date:** [May 24, 2020, 6:28am UTC](https://forums.swift.org/t/modify-accessors/31872/239 "2020-05-24T06:28:55Z")

</div>

> [@anandabits](#):
>
> I’m more concerned about the difference between writeback semantics and modify semantics from the perspective of the user. If one needs to guarantee preservation of the original value without a _guarantee_ that the property or subscript has writeback semantics a defensive copy would be necessary. This is a copy that isn’t necessary today, which means that introducing a `modify` accessor to an existing property as an optimization could break existing code using that property in a subtle way.

@anandabits, could you please elaborate with an example of what you mean?

---

<div class="post-metadata">

**Author:** ![mattrips](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mattrips/32/4079_2.png) [@mattrips](https://forums.swift.org/u/mattrips)\
**Post date:** [May 24, 2020, 6:33am UTC](https://forums.swift.org/t/modify-accessors/31872/240 "2020-05-24T06:33:38Z")

</div>

> [@ben-cohen](#):
>
> it is also possible to supply _both_ a `modify` and a `set` . The `set` will be called in the case of straight assignment, which may be more efficient than first fetching/creating a value to then be overwritten:

I noticed that `Array`'s implementation of `subscript` uses only a `_modify`. Is there a reason why `Array` isn't taking advantage of the optimization of a `set` when performing straight assignments?

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [May 24, 2020, 2:22pm UTC](https://forums.swift.org/t/modify-accessors/31872/241 "2020-05-24T14:22:55Z")

</div>

By its nature, array’s mutating subscript always involves an existing value at the position.

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [June 15, 2020, 11:58am UTC](https://forums.swift.org/t/modify-accessors/31872/242 "2020-06-15T11:58:11Z")

</div>

Late to the game but thanks, this is exactly what has been confusing me. I can't see the purpose of the coroutine concept here, when all you really do seems to be to allow callers to run a modification closure on your backing property.

I can understand that there are other reasons for introducing (semi-) co-routines, perhaps related to SwiftUI or (let's hope:) async/await, and perhaps I am missing something.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [June 27, 2020, 4:01pm UTC](https://forums.swift.org/t/modify-accessors/31872/243 "2020-06-27T16:01:16Z")

</div>

> [@Alejandro\_Martinez](#):
>
> - I like `yield` not only because it says what it does, but also because is the common name used to refer to _coroutines_ .
> 
> ...
> 
> - The usage of `defer` is quite clear once you understand what's going on. Is not obvious for a newcomer but honestly **this feature is a little advanced IMO**.

Is it, though? One could argue that by leaving such sharp edges around, we _make_ it an advanced feature which is not accessible to newcomers.

Especially if this generalises to all coroutines. Suddenly coroutines themselves become an advanced feature because of how careful you need to be.

Given how the language has developed since this pitch, I’m more in favour of a yield statement with a mandatory cancellation handler, like this:

```
  yield &myThing else {
    // yield failed (was cancelled). Clean up.
    // similar to guard, you must return from this block.
  }
  // yield was successful. Do post-processing.

```

It’s simple to understand the possible control flow when you have it written there, and difficult to understand (with potentially disastrous consequences) if you don’t. Even experienced developers appreciate when things are made obvious.

But we should really move forward with this. I keep forgetting it’s not actually part of the language yet.

---

<div class="post-metadata">

**Author:** ![AnotherUser](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anotheruser/32/14927_2.png) [@AnotherUser](https://forums.swift.org/u/AnotherUser)\
**Post date:** [June 27, 2020, 8:00pm UTC](https://forums.swift.org/t/modify-accessors/31872/244 "2020-06-27T20:00:05Z")

</div>

I like this. IMO you've cracked it.

[Previous page](https://forums.swift.org/t/modify-accessors/31872.md?page=11)

[Next page](https://forums.swift.org/t/modify-accessors/31872.md?page=13)
