As part of our ongoing work to bring non-copyable types to Swift [1] [2] [3] [4], we've realized that there are a lot of core Swift constructs that imply copying, including variable initialization (let
and var
declarations), switch statements, and if let
optional unwrapping.
To make these useful for noncopyable types, we'd like to add new "binding" or "reference" constructs that allow you to work with a value in various ways without any implicit copying. In the process of working out these ideas, we've realized that they can provide real benefits even for copyable types.
The full pitch with more complete details is in this gist where I can edit it to incorporate people's feedback but the core idea is to add new uses of borrow
and inout
keywords that allow you to write things like the following:
if inout y = &optional {
// `y` is a reference to the payload of `optional`
// So the following mutates it in-place
y += 1
}
// "&" below indicates `enum_value` might get modified
// It's required if there are any `inout` references in the
// switch statement.
switch &enum_value {
case .a(borrow x):
// `x` is a read-only reference to the payload
// so this calls a method on that payload
// without a potentially expensive copy of `x`
x.someMethod()
case .b(inout y):
// `y` is a read-write reference to the payload
// so this mutates the payload in-place
y.someMutatingMethod()
}
I look forward to the discussion!