I'm starting this thread since there seems to be a lot to discuss related to Swift's patterns.
The subject has come up in at least three recent threads:
Allow optional unwrapping in where clause
Unwrapping and value binding patterns in the condition of ternary expressions
SE-0231 — Optional iteration
It would be interesting to see if Swift's patterns (in general, not just optional patterns) could be made more uniform, and thus easier to use/understand/remember/learn/teach, while at the same time, if we're lucky, solve problems like the ones in the above threads as a by-product.
If not, we can at least learn something by understanding the reasons for why that is not the case.
As an initial example:
let optInt: Int? = 123
let optInts: [Int?] = [123, 456, 789]
// Note that
// `case let .some(v)` works for both the if statement and the for-in loop:
if case let .some(v) = optInt { print(v) } // prints 123
for case let .some(v) in optInts { print(v) } // prints 123 456 789
// and
// `case let v?`, a terser form, also works for both:
if case let v? = optInt { print(v) } // prints 123
for case let v? in optInts { print(v) } // prints 123 456 789
// but
// `let v`, the tersest form, only works for the if statement, WHY?
if let v = optInt { print(v) } // prints 123
for let v in optInts { print(v) } // ERROR: 'let' pattern cannot appear nested
// in an already immutable context
// (I don't understand that error message.)
And related to for-in loops and SE-0231, could the right side of the in
do some pattern matching too, in some way that is consistent with other uses of patterns in the language?