Hacker News new | ask | show | jobs
by heydenberk 4386 days ago
Optional binding in JavaScript is a misfeature, and Ruby's looks that way too, because 99% of the time when you do this:

    if (hasAccess = true) {
        doSomething();
    }
you meant to compare, not assign. So when I saw this Ruby example, I was not amused:

    if current_user = find_current_user
       notify_user(current_user)
    end
However, the Swift equivalent is the best of both worlds:

    if let currentUser = findCurrentUser() {
       notifyUser(currentUser)
    }
1 comments

The thing that's interesting about optional binding is Swift is that it is a special construct for unwrapping optionals, not a normal assignment. If you try to bind to something that is not an optional using that syntax, it won't work. For example:

  if let currentUserIsAuthorized = true { // COMPILE ERROR
    ...
  }
This makes it useful for the one case where you'd actually want it without introducing any pitfalls, because using it incorrectly will be a syntax or type error.