SE-0345: `if let` shorthand for shadowing an existing optional variable

Yes -- a hypothetical future if inout &foo syntax would work in the same way as Kotlin's type-refinement syntax. Mutations in the inner scope would also apply to the outer scope.

More discussion about potential upcoming borrow variables can be found in "A roadmap for improving Swift performance predictability".

// Kotlin, type refinement
var foo: String? = "foo"
print(foo?.length) // 3

if (foo != null) {
    foo = "baaz"
    print(foo.length) // 4
}

print(foo?.length) // 4
// Swift, `if var`
var foo: String? = "foo"
print(foo?.count) // 3

// creates a separate copy, that is mutable:
if if var foo {
    foo = "baaz"
    print(foo.count) // 4
}

print(foo?.count) // 3
// Swift, hypothetical `if inout`
var foo: String? = "foo"
print(foo?.cound) // 3

// borrows and mutates the storage of the existing foo variable
if inout &foo {
    foo = "baaz"
    print(foo.count) // 4
}

print(foo?.count) // 4
2 Likes