[swift-evolution] [Idea] Remove optional pattern binding

David Waite david at alkaline-solutions.com
Mon May 2 15:08:06 CDT 2016

> The reason is simple: most developers don’t grok pattern matching.  Particularly for people new to swift, “if let” is taught as a magic for dealing with optionals (which it is). This is a very useful mechanic when working in Swift, and this way of thinking is fine.  Optionals are very prominent, and having special sugar for dealing with them is important, even as people grow to become swift experts in time.
> Going with the proposal would definitely simplify the language ('if case’ could probably go away), but would force everyone, all the time, to think about pattern matching.  This would be a barrier to entry that many programmers should never have to face.  The fact that many people don’t think about things in terms of pattern matching is the root cause for the comments about “it seems weird that the question mark is on the LHS of the assignment”.
> Finally, some may argue that making pattern matching more prominent would help teach pattern matching and get more people to use it.  That may be true, but our goal here is to build a pragmatic language that helps people get things done, not push to one specific language feature.  I personally love pattern matching (and was the one who drove and implemented the Swift 2 pattern matching enhancements), but it is an esoteric and special case feature.  It makes sense for it to be “buried” under “if case”: those who are unfamiliar with the syntax have something they can google for.
My issue is that while one needs to have a special behavior in this case to combine conditional logic and variable assignment, the current shorthand is nonintuitive/inconsistent. The current syntax makes it look like you are saying “let y=x”, and that now assignment has different behaviors if you are inside or outside a conditional. Why does assignment sometime cast off optionality?

let x:Optional = 1 // x: Int? = 1

if let y = x { 
     print(y.dynamicType) // Int
let y = x
print(y.dynamicType) // Optional<Int>

If there were a syntax like “if let y = some x”, then it would be clear that there is more to this statement than an assignment, it would make it clearer why you can’t cast off optionality on other assignments, as well as possibly being a segue to learning about full pattern matching.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160502/a46c4dde/attachment.html>

More information about the swift-evolution mailing list