Set-only subscripts

Well, lessee. That's equivalent to:

{ opt: inout Optional in opt?.mutatingMethod() }(&x[b])

But in the scenario you posit, there's no Optional that you can inout (you can only “out” the Optional). So it would at least require some special rules in the language to describe how this works. Furthermore, to get it to work you'd have to read with one subscript's getter and write back with a different subscript's setter. That adds a lot of language complexity and breaks coherence with modify accessors.

If you want to create an API that allows you to write the semantic equivalent of x[b]?.mutatingMethod() but doesn't allow the semantic equivalent of x[b] = nil, it's easy to write that as a mutating method. Here's how you could add such an API to Dictionary, for example:

extension Dictionary {
  /// Returns the result of calling `body` on the value corresponding to `k`
  /// if `k` is a key in `self`; returns `nil` otherwise.
  @discardableResult
  mutating func mutateValue<Result>(
    ifKeyExists k: Key, body: (inout Value)->Result
  ) -> Result? {
    guard let i = index(forKey: k) else { return nil }
    return body(&values[i])
  }
}
2 Likes