Pitch: `borrow` and `inout` declaration keywords

It was in func foo(inout x: T) form in Swift 1 (or 2?), then changed to the way it is now (any language historians to know why? Something about simplifying compiler IIRC).

That's "easy" :wink:. Create a new (ideally renamed, but could be the same name) modifier in the other position, disallow having both at once (per declaration), then soft deprecate (with a fix-it suggestion) → then deprecate the elder inout over a couple of releases, potentially changing from a "per declaration" ruling to a "per file" or module – eventually most code will follow the new way (having Apple established swift linting tool built into Xcode out of the box with canonical presets would speed such things up). Make sure to keep calm and ignore the angry noise here or on twitter about the change during the period of transition. In a few years time the usage of the older way becomes insignificantly small to be important. Done. :champagne:.


I'm just popping in to state my enthusiastic support for this idea! I'd start heavily using both variants as soon as they become available.

The inability to mutate enum payloads in place without absurd and/or unreliable contortions has been one reason I've come to avoid using enum types whenever possible. inout bindings would eliminate this pain, opening up refreshingly simple design choices.

Borrowing variables would make a similarly large quality-of-life benefit. For example, another source of painful contortions for me is the need to avoid copying generic Element types into temporary local variables while I'm working on data structure implementations. It seems borrow variables would be a great way to fix that.

I have no strong opinions about the proposed syntax. (Please don't make it too weird.)


Why are immutable borrows exclusive? We want to be able to borrow a member of a borrowed value, don’t we? What’s the difference between borrowing myAlias.foo and myAlias.self? Or myAlias.resilientPropertysThatHappensToReturnSelf?

“Exclusivity” in Swift refers to the general rule; I think Michael is using “immutable exclusivity” to mean the rule for non-mutating accesses under that, which does allow multiple simultaneous accesses.

1 Like

Ok, I think that still admits the use of alias, unless the concern is about something like:

var x = 42
alias y = x
someFunc(&x) // error: `x` is already borrowed

Perhaps I’m not understanding the full consequences here.

To me it looks like Michael's comment about exclusivity assumed the "substitute name" meaning of alias as self evident and jumped right ahead into explaining how a borrow is different from a substitute name. I'd take this as a hint that alias could be a confusing name for the feature.


I'm going to mostly stay clear of the bikeshedding this time, but I'll note that both mutating and inout exist today and refer to copyable move-in/move-out values. Having them diverge would be a bit confusing for existing mutating methods.

Re: placement of inout today: as fclout neatly summarized, it's part of function types, but not arbitrary other types, and doesn't stand on its own as a type modifier. We have at least one other modifier that works like this: @escaping. Unfortunately, this doesn't suggest any perfect syntax to me that both maintains the analogy and also visually binds appropriately.

I am glad to see that these bindings formally extend to end-of-scope, and wish to explicitly support that decision.

I don't understand why global variables are excluded. Formally, stored global variables are no different from any other computed property at the use site, except for the under-the-table guarantee that if they are in the current module and do not have observing accessors, they will have a consistent address in inout-to-pointer conversions.


I agree that there doesn’t seem to be a good reason to exclude global variables from being accessed this way. There aren’t any conceptual or implementation problems this protects against which aren’t already present because of, say, instance properties of classes.


Right, and this question was settled in SE-0031 back in 2016, which the calendar tells me was somehow seven years ago.

var parameters were removed from the language in SE-0003; explicit let parameters, which probably no one remembers, were also removed from the language in SE-0053.


Tying back to the start of the thread where we discussed having mutable bindings inferred from &value, I’d like to see something like borrow used on the side of the value:

let x = 5
let y /*: borrow Int*/ = borrow x

var m = 5
var n /*: inout Int*/ = &m

I think inferring ownership from either the type or the value of the binding fits Swift’s design better. Statements like for and switch don’t have a keyword like let because it’s verbose, and ownership can be clear from context. Additionally, function types only expose their types (without labels unfortunately), so it would make sense to naturally express a (borrow Int) -> Int. I’m not necessarily advocating for the above syntax, but I do think we should end up with something that’s part of the type or the declaration’s right hand side.


(Off topic)
Alas!... I wish this to be reverted. This shouldn't have been accepted in the first place (my personal opinion); as it eliminates implicit returns and also complex for beginners to understand in terms of variable redeclaration.

1 Like

Is this basically about whether inout refers to the variable binding or the type?

If we look at SE-31, we have the following arguments:

  • inout on the name side is less desirable because it creates inconsistency with function types that have inout parameters
  • inout on the name side is notationally similar to labeled arguments
  • inout on the name side makes it impossible to use inout as a variable name
  • inout on the type side matches similar patterns in other languages, like Rust borrows, that we could want to add to Swift some day

I (possibly incorrectly) view the bar to revisit a "settled" proposal as simply that we learned new things that are relevant to it, and in this case we learned (7 years later) that once the rubber hits the road, one of the motivations for it is actually backwards!

IMO, there's one new good reason to move inout back to the variable side (it results in a more consistent syntax for mutable borrows, the opposite of what we thought before) and the main reasons to keep it where it is are that the function type syntax would be less consistent and it would be a source-breaking change. It's reasonable to end up deciding that inout as a variable introducer is not a good idea. If that's the case, naming the reasons that we're not going to do it will help move on.

This is also possibly a cautionary tale about using far-out features as the justification for anything, although I believe we got a lot better with this over the years.


You are correct. Thank you. = ).

+1. I like this better than both the proposal and the alternatives downthread. It addresses two concerns of mine:

  • inout as a muddled metaphor when we’re not talking about functions
  • borrow as an overloaded term when used as the term for both the action on a value (i.e. in an expression) and the behavior of a variable (i.e. in a declaration)

I also think that grid is the best, most concise casual explanation of these concepts I’ve seen. Even sort of mostly understanding these terms, I still find this helpful! It’s something I’d draw on a whiteboard any time I’m teaching these concepts.

I don’t think any terminology schema I’ve heard, including this one, makes the concept completely transparent to someone encountering it for the first time — but this alternative comes closest of the options I’ve seen to Swift’s ideal of progressive disclosure. And for the experts, I like how the terms roll off the tongue in context as I try sample sentences in my head, discussing things to a hypothetical colleague or student:

  • “A borrowing variable would improve performance here”
  • “Oops, var x = things[i] just means x is itself mutable; we need a mutating variable to modify the array itself”
  • “You can’t own a struct value that somebody else owns, except by making a copy. If you want to avoid the copy, you’ll need to borrow the value….” (Aside: Does this line of explanation lead to an incorrect conclusion? I think borrow will still induce copies in some situations…?)

While I'm mostly okay with mutating, this part in particular feels like the weakest link. I can already picture myself explaining that, yes, "mutable" and "mutating" might sound like the same thing but there's actually very important differences.

I don't feel like mutating conveys well enough by itself the ownership significance, which is IMO the more important and less intuitive thing for the keyword to convey. So I continue to lean towards something like borrow(var) or anything else that unites the items in the borrowed column a bit more explicitly.


I agree, it should be relatively easy to type. Just another suggestion:

ref x = y      // immutable borrow
ref var x = &y // mutable borrow

for ref x in array {}
for ref var x in &array {}

I think that borrow and inout are very awkward declaration keywords. Here's my suggestion:

var x = 7
alias y = x   // immutable borrow
alias z = &x  // mutable borrow

The bindings/types (e.g. when inspected with Xcode) would be:

var x: Int
alias y: Int
mutating alias z: Int

You are suggesting Rust’s ampersand, which means something different than Swift’s ampersand. Swift’s ampersand means “this value could get mutated”. Rust’s means “this statement forms a reference to this binding”. We are not going to change the meaning of Swift’s ampersand, for source stability among other reasons.


The ampersand is not intrinsically related to pointers, and it is not a marker for unsafety. People associated them because they come up a lot together in C interop, and C’s ampersand is confusingly related as well. However, in Swift the ampersand is intended as a marker for possible mutations.

1 Like