Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Swift, what does this specific syntax mean?

I've been attempting to follow some iOS Swift tutorials for connecting to Parse.com

codementor.io tutorial:

  loginViewController.fields = .UsernameAndPassword | .LogInButton | .PasswordForgotten | .SignUpButton | .Facebook | .Twitter

makeschool tutorial

  loginViewController.fields = [.UsernameAndPassword, .LogInButton, .SignUpButton, .PasswordForgotten, .Facebook]

I assume the former is Switch 1.x, and thelatter is Swift 2. From context they appear to be doing the same thing, but I haven't yet found the language references for the change in syntax. Awfully hard to search for dots, pipes and commas... can someone explain the syntax in each snippet? (I'm working on reading through the language specification, but would be fun to actually get an app to work!)

like image 901
Ultrasaurus Avatar asked Nov 23 '15 03:11

Ultrasaurus


1 Answers

The old Swift 1 syntax is based on the way you deal with option sets in C and Objective-C: you store an option set in an integer type and use bitwise operators (| and & and ~) to manipulate them. So .UsernameAndPassword | .LogInButton means an option set in which both the .UsernameAndPassword and the .LogInButton options are included. In the old syntax, you use nil to represent an empty option set (in which no options are included), which is not obvious based on the syntax for a non-empty set.

Chris Lattner described the changed syntax in WWDC 2015 Session 106: What's New in Swift. First he describes the problems with the old syntax:

The problem is, when you get to the other syntaxes you end up using, it is a bit less nice. You create an empty-option set with nil -- it doesn't make sense because option sets and optionals are completely different concepts and they're conflated together. You extract them with bitwise operations, which is a pain and super error-prone, and you can get it wrong easily.

Then he describes the new approach:

But Swift 2 solves this. It makes option sets set-like. That means option sets and sets are now formed with square brackets. That means you get empty sets with an empty set of square brackets, and you get the full set of standard set API to work with option sets.

The reason the new syntax works is because OptionSetType conforms to the ArrayLiteralConvertible protocol (indirectly, by conforming to SetAlgebraType). This protocol allows a conforming object to be initialized using an array literal, by having an init that takes a list of elements.

In the new Swift 2 syntax, [ .UsernameAndPassword, .LogInButton ] represents an option set containing both the .UsernameAndPassword and the .LogInButton options. Note that it looks just like the syntax by which you can initialize a plain old Set: let intSet: Set<Int> = [ 17, 45 ]. The new syntax makes it obvious that you specify an empty option set as [].

like image 130
rob mayoff Avatar answered Nov 15 '22 09:11

rob mayoff