\chapter{Related Work} \label{s:RelatedWork} An enumeration type exist in many popular programming languages, both past and present, \eg Pascal~\cite{Pascal}, Ada~\cite{Ada}, \Csharp~\cite{Csharp}, \CC, Go~\cite{Go}, Java~\cite{Java}, Modula-3~\cite{Modula-3}, Rust~\cite{Rust}, Swift~\cite{Swift}, Python~\cite{Python}, and the algebraic data-type in functional programming. Among theses languages, there are a large set of overlapping features, but each language has its own unique extensions and restrictions. \section{Pascal} \lstnewenvironment{pascal}[1][]{\lstset{language=pascal,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} Classic Pascal has the \lstinline[language=pascal]{const} declaration binding a name to a constant literal/expression. \begin{pascal} const one = 0 + 1; Vowels = set of (A,E,I,O,U); NULL = NIL; PI = 3.14159; Plus = '+'; Fred = 'Fred'; \end{pascal} The enumerator type is inferred from the constant-expression type. There is no notion of an ordered set, modulo the \lstinline[language=pascal]{set of} type. Free Pascal~\cite[\S~3.1.1]{FreePascal} is a modern, object-oriented version of classic Pascal, with a C-style enumeration type. Enumerators must be assigned in ascending numerical order with a constant expression and the range can be non-consecutive. \begin{pascal} Type EnumType = ( one, two, three, forty @= 40@, fortyone ); \end{pascal} Pseudo-functions @Pred@ and @Succ@ can only be used if the range is consecutive. The underlying type is an implementation-defined integral-type large enough to hold all enumerated values; it does not have to be the smallest possible type. The integral size can be explicitly specified using compiler directive @$PACKENUM@~$N$, where $N$ is the number of bytes, \eg: \begin{pascal} Type @{$\color{red}\$$PACKENUM 1}@ SmallEnum = ( one, two, three ); @{$\color{red}\$$PACKENUM 4}@ LargeEnum = ( BigOne, BigTwo, BigThree ); Var S : SmallEnum; { 1 byte } L : LargeEnum; { 4 bytes} \end{pascal} \section{Ada} \lstnewenvironment{ada}[1][]{\lstset{language=[2005]Ada,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},literate={'}{\ttfamily'\!}1}\lstset{#1}}{} An Ada enumeration type is an ordered list of constants, called \Newterm{literals} (enumerators). \begin{ada} type RGB is ( @Red@, @Green@, Blue ); -- 3 literals (enumerators) \end{ada} No other enumerators are assignable to objects of this type. Enumerators without an explicitly designated constant value are auto-initialized: from left to right, starting at zero or the next explicitly initialized constant, incrementing by 1. To explicitly set enumerator values, \emph{all} enumerators must be set in \emph{ascending} order, \ie there is no auto-initialization. \begin{ada} type RGB is ( Red, Green, Blue ); @for RGB use ( Red => 10, Green => 20, Blue => 30 );@ -- ascending order \end{ada} Hence, the position, value, label tuples are: \begin{ada} (0, 10, RED) (1, 20, GREEN) (2, 30, BLUE) \end{ada} Like C, Ada enumerators are unscoped, \ie enumerators declared inside of an enum are visible (projected) into the enclosing scope. Note, Ada is case-\emph{insensitive} so names may appear in multiple forms and still be the same name (a questionable design decision). The enumeration operators are the ordering operators, @=@, @<@, @<=@, @=@, @/=@, @>=@, @>@, where the ordering relation is given implicitly by the sequence of enumerators, which is always ascending. Ada enumerators are overloadable. \begin{ada} type Traffic_Light is ( @Red@, Yellow, @Green@ ); \end{ada} Like \CFA, Ada uses an advanced type-resolution algorithm, including the left-hand side of assignment, to disambiguate among overloaded names. \VRef[Figure]{f:AdaEnumeration} shows how ambiguity is handled using a cast, \eg \lstinline[language=ada]{RGB'(Red)}. \begin{figure} \begin{ada} with Ada.Text_IO; use Ada.Text_IO; procedure test is type RGB is ( @Red@, Green, Blue ); type Traffic_Light is ( @Red@, Yellow, Green ); -- overload procedure @Red@( Colour : RGB ) is begin -- overload Put_Line( "Colour is " & RGB'Image( Colour ) ); end Red; procedure @Red@( TL : Traffic_Light ) is begin -- overload Put_Line( "Light is " & Traffic_Light'Image( TL ) ); end Red; begin @Red@( Blue ); -- RGB @Red@( Yellow ); -- Traffic_Light @Red@( @RGB'(Red)@ ); -- ambiguous without cast end test; \end{ada} \caption{Ada Enumeration Overload Resolution} \label{f:AdaEnumeration} \end{figure} Ada provides an alias mechanism, \lstinline[language=ada]{renames}, for aliasing types, which is useful to shorten package names. \begin{ada} OtherRed : RGB renames Red; \end{ada} which suggests a possible \CFA extension to @typedef@. \begin{cfa} typedef RGB.Red OtherRed; \end{cfa} There are three pairs of inverse enumeration pseudo-functions (attributes): @'Pos@ and @'Val@, @'Enum_Rep@ and @'Enum_Val@, and @'Image@ and @'Value@, \begin{cquote} \lstDeleteShortInline@ \setlength{\tabcolsep}{15pt} \begin{tabular}{@{}ll@{}} \begin{ada} RGB'Pos( Red ) = 0; RGB'Enum_Rep( Red ) = 10; RGB'Image( Red ) = "RED"; \end{ada} & \begin{ada} RGB'Val( 0 ) = Red RGB'Enum_Val( 10 ) = Red RGB'Value( "Red" ) = Red \end{ada} \end{tabular} \lstMakeShortInline@ \end{cquote} These attributes are important for IO. An enumeration type @T@ also has the following attributes: @T'First@, @T'Last@, @T'Range@, @T'Pred@, @T'Succ@, @T'Min@, and @T'Max@, producing an intuitive result based on the attribute name. Ada allows the enumerator label to be a character constant. \begin{ada} type Operator is ( '+', '-', '*', '/' ); Op : Operator; \end{ada} which is syntactic sugar for the label and not character literals from the predefined type @Character@. The purpose is readability using character literals rather than names. \begin{ada} Op := '+'; case Op is -- all enumerators must appear when '+' => ... ; when '-' => ... ; when '*' => ... ; when '/' => ... ; end case; \end{ada} Arrays of character enumerators can be treated as strings. \begin{ada} Ops : array( 0..3 ) of Operator; Ops := @"+-*/"@; -- string assignment to array elements Ops := @"+-" & "*/"@; -- string concatenation and assignment for Op of Ops loop Put_Line( Operator'Image( Op ) ); end loop; \end{ada} Ada's @Character@ type is defined as a character enumeration across all Latin-1 characters. Ada's boolean type is defined as a special enumeration, which can be used in conditions. \begin{ada} type Boolean is (False, True); -- False / True not keywords @Flag@ : Boolean; if @Flag@ then ... -- conditional \end{ada} Since only types derived from @Boolean@ can be a conditional, @Boolean@ is essentially a builtin type. Ada provides \emph{consecutive} subtyping of an enumeration using \lstinline[language=ada]{range}. \begin{ada} type Week is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); subtype Weekday is Week @range Mon .. Fri@; subtype Weekend is Week @range Sat .. Sun@; Day : Week; \end{ada} Hence, the ordering of the enumerators is crucial to provide the necessary ranges. An enumeration type can be used in the Ada \lstinline[language=ada]{case} (switch) and iterating constructs. \begin{cquote} \lstDeleteShortInline@ \setlength{\tabcolsep}{15pt} \begin{tabular}{@{}ll@{}} \begin{ada} case Day is when @Mon .. Fri@ => ... ; when @Sat .. Sun@ => ... ; end case; \end{ada} & \begin{ada} case Day is when @Weekday@ => ... ; -- subtype ranges when @Weekend@ => ... ; end case; \end{ada} \end{tabular} \end{cquote} \begin{cquote} \setlength{\tabcolsep}{12pt} \begin{tabular}{@{}lll@{}} \begin{ada} for Day in @Mon .. Sun@ loop ... end loop; \end{ada} & \begin{ada} for Day in @Weekday@ loop ... end loop; \end{ada} & \begin{ada} for Day in @Weekend@ loop ... end loop; \end{ada} \end{tabular} \lstMakeShortInline@ \end{cquote} An enumeration type can be used as an array dimension and subscript. \begin{ada} Lunch : array( @Week@ ) of Time; for Day in Week loop Lunch( @Day@ ) := ... ; -- set lunch time end loop; \end{ada} \section{\CC} \label{s:C++RelatedWork} \lstnewenvironment{c++}[1][]{\lstset{language=[GNU]C++,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} \CC is largely backwards compatible with C, so it inherited C's enumerations. However, the following non-backwards compatible changes have been made. \begin{cquote} 7.2 Change: \CC objects of enumeration type can only be assigned values of the same enumeration type. In C, objects of enumeration type can be assigned values of any integral type. \\ Example: \begin{c++} enum color { red, blue, green }; color c = 1; $\C{// valid C, invalid C++}$ \end{c++} \textbf{Rationale}: The type-safe nature of \CC. \\ \textbf{Effect on original feature}: Deletion of semantically well-defined feature. \\ \textbf{Difficulty of converting}: Syntactic transformation. (The type error produced by the assignment can be automatically corrected by applying an explicit cast.) \\ \textbf{How widely used}: Common. \end{cquote} \begin{cquote} 7.2 Change: In \CC, the type of an enumerator is its enumeration. In C, the type of an enumerator is @int@. \\ Example: \begin{c++} enum e { A }; sizeof(A) == sizeof(int) $\C{// in C}$ sizeof(A) == sizeof(e) $\C{// in C++}$ /* and sizeof(int) is not necessary equal to sizeof(e) */ \end{c++} \textbf{Rationale}: In \CC, an enumeration is a distinct type. \\ \textbf{Effect on original feature}: Change to semantics of well-defined feature. \\ \textbf{Difficulty of converting}: Semantic transformation. \\ \textbf{How widely used}: Seldom. The only time this affects existing C code is when the size of an enumerator is taken. Taking the size of an enumerator is not a common C coding practice. \end{cquote} Hence, the values in a \CC enumeration can only be its enumerators (without a cast). While the storage size of an enumerator is up to the compiler, there is still an implicit cast to @int@. \begin{c++} enum E { A, B, C }; E e = A; int i = A; i = e; $\C{// implicit casts to int}$ \end{c++} \CC{11} added a scoped enumeration, \lstinline[language=c++]{enum class} (or \lstinline[language=c++]{enum struct}), where the enumerators are accessed using type qualification. \begin{c++} enum class E { A, B, C }; E e = @E::@A; $\C{// qualified enumerator}$ e = B; $\C{// B not in scope}$ \end{c++} \CC{20} supports explicit unscoping with a \lstinline[language=c++]{using enum} declaration. \begin{c++} enum class E { A, B, C }; @using enum E;@ E e = A; $\C{// direct access}$ e = B; $\C{// direct access}$ \end{c++} \CC{11} added the ability to explicitly declare the underlying \emph{integral} type for \lstinline[language=c++]{enum class}. \begin{c++} enum class RGB @: long@ { Red, Green, Blue }; enum class rgb @: char@ { Red = 'r', Green = 'g', Blue = 'b' }; enum class srgb @: signed char@ { Red = -1, Green = 0, Blue = 1 }; \end{c++} There is no implicit conversion from the \lstinline[language=c++]{enum class} type and to its declared type. \begin{c++} rgb crgb = rgb::Red; char ch = rgb::Red; ch = crgb; $\C{// disallowed}$ \end{c++} Finally, there is no mechanism to iterate through an enumeration nor use the enumeration type to declare an array dimension. \section{C\raisebox{-0.7ex}{\LARGE$^\sharp$}\xspace} % latex bug: cannot use \relsize{2} so use \LARGE \label{s:Csharp} \lstnewenvironment{csharp}[1][]{\lstset{language=[Sharp]C,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} % https://www.tutorialsteacher.com/codeeditor?cid=cs-mk8Ojx \Csharp is a dynamically-typed programming-language with a scoped, integral enumeration-type similar to C/\CC enumeration. \begin{csharp} enum Weekday : byte { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun@,@ }; \end{csharp} The default underlying type is @int@, with auto-incrementing, implicit/explicit initialization, terminator comma, and optional integral typing (default @int@) A method cannot be defined in an enumeration type. As well, there is an explicit bidirectional conversion between an enumeration and its integral type, and an implicit conversion to the enumerator label in display contexts. \begin{csharp} int day = (int)Weekday.Fri; $\C{// day == 10}$ Weekday weekday = (Weekdays)42; $\C{// weekday == 42, logically invalid}$ Console.WriteLine( Weekday.Fri ); $\C{// print Fri}$ string mon = Weekday.Mon.ToString(); $\C{// mon == "Mon"}$ \end{csharp} The @Enum.GetValues@ pseudo-method retrieves an array of the enumeration constants for looping over an enumeration type or variable. \begin{csharp} foreach ( Weekday constant in @Enum.GetValues@( typeof(Weekday) ) ) { Console.WriteLine( constant + " " + (int)constant ); // label, position } \end{csharp} The @Flags@ attribute creates a bit-flags enumeration, allowing bitwise operators @&@, @|@, @~@ (complement), @^@ (xor). \begin{csharp} @[Flags]@ public enum Weekday { None = 0x0, Mon = 0x1, Tue = 0x2, Wed = 0x4, Thu = 0x8, Fri = 0x10, Sat = 0x20, Sun = 0x40, Weekend = @Sat | Sun@, Weekdays = @Mon | Tue | Wed | Thu | Fri@ } Weekday meetings = @Weekday.Mon | Weekday.Wed@; // 0x5 \end{csharp} \VRef[Figure]{CsharpFreeVersusClass} shows an enumeration with free routines for manipulation, and embedding the enumeration and operations into an enumeration class. The key observation is that an enumeration class is just a structuring mechanism without any additional semantics. % https://learn.microsoft.com/en-us/dotnet/api/system.enum?view=net-8.0 \begin{figure} \centering \lstDeleteShortInline@ \begin{tabular}{@{}l|l@{}} \multicolumn{1}{@{}c|}{non-object oriented} & \multicolumn{1}{c@{}}{object oriented} \\ \hline \begin{csharp} public class Program { enum Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; static bool isWeekday( Weekday wd ) { return Weekday.Mon <= wd && wd <= Weekday.Fri; } static bool isWeekend( Weekday wd ) { return Weekday.Sat <= wd && wd <= Weekday.Sun; } public static void Main() { Weekday day = Weekday.Sat; Console.WriteLine( isWeekday( day ) ); Console.WriteLine( isWeekend( day ) ); } } \end{csharp} & \begin{csharp} public class Program { public @class@ WeekDay { public enum Weekday { Mon=-4, Tue=-3, Wed=-2, Thu=-1, Fri=0, Sat=1, Sun=2 }; Weekday day; public bool isWeekday() { return day <= 0; } public bool isWeekend() { return day > 0 } public WeekDay( Weekday d ) { day = d; } } public static void Main() { WeekDay cday = new WeekDay( WeekDay.Weekday.Sat ); Console.WriteLine( cday.isWeekday() ); Console.WriteLine( cday.isWeekend() ); } } \end{csharp} \end{tabular} \lstMakeShortInline@ \caption{\Csharp: Free Routine Versus Class Enumeration} \label{CsharpFreeVersusClass} \end{figure} \section{Golang} \lstnewenvironment{Go}[1][]{\lstset{language=Go,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} Golang provides a mechanism similar to classic Pascal \lstinline[language=pascal]{const}, binding a name to a constant literal/expression (pseudo enumeration). \begin{Go} const ( R = 0; G; B ) $\C{// implicit: 0 0 0}$ const ( Fred = "Fred"; Mary = "Mary"; Jane = "Jane" ) $\C{// explicit: Fred Mary Jane}$ const ( S = 0; T; USA = "USA"; U; V = 3.1; W ) $\C{// type change, implicit/explicit: 0 0 USA USA 3.1 3.1}$ \end{Go} Constant names are unscoped and must be unique (no overloading). The first enumerator \emph{must} be explicitly initialized; subsequent enumerators can be implicitly or explicitly initialized. Implicit initialization is the previous (predecessor) enumerator value. Auto-incrementing is supported by the keyword \lstinline[language=Go]{iota}, available only in the \lstinline[language=Go]{const} declaration. The \lstinline[language=Go]{iota} is a \emph{per \lstinline[language=golang]{const} declaration} integer counter, starting at zero and implicitly incremented by one for each \lstinline[language=golang]{const} identifier (enumerator). \begin{Go} const ( R = @iota@; G; B ) $\C{// implicit: 0 1 2}$ const ( C = @iota + B + 1@; G; Y ) $\C{// implicit: 3 4 5}$ \end{Go} An underscore \lstinline[language=golang]{const} identifier advances \lstinline[language=Go]{iota}. \begin{Go} const ( O1 = iota + 1; @_@; O3; @_@; O5 ) // 1, 3, 5 \end{Go} Auto-incrementing stops after an explicit initialization. \begin{Go} const ( Mon = iota; Tue; Wed; // 0, 1, 2 @Thu = 10@; Fri; Sat; Sun ) // 10, 10, 10, 10 \end{Go} Auto-incrementing can be restarted with an expression containing \emph{one} \lstinline[language=Go]{iota}. \begin{Go} const ( V1 = iota; V2; @V3 = 7;@ V4 = @iota@; V5 ) // 0 1 7 3 4 const ( Mon = iota; Tue; Wed; // 0, 1, 2 @Thu = 10;@ Fri = @iota - Wed + Thu - 1@; Sat; Sun ) // 10, 11, 12, 13 \end{Go} Note, \lstinline[language=Go]{iota} is advanced for an explicitly initialized enumerator, like the underscore @_@ identifier. Basic switch and looping are possible. \begin{cquote} \lstDeleteShortInline@ \setlength{\tabcolsep}{15pt} \begin{tabular}{@{}ll@{}} \begin{Go} day := Mon; switch day { case Mon, Tue, Wed, Thu, Fri: fmt.Println( "weekday" ); case Sat, Sun: fmt.Println( "weekend" ); } \end{Go} & \begin{Go} for i := Mon; i <= Sun; i += 1 { fmt.Println( i ) } \end{Go} \end{tabular} \lstMakeShortInline@ \end{cquote} The loop prints the values from 0 to 13 because there is no actual enumeration. \section{Java} \lstnewenvironment{Java}[1][]{\lstset{language=Java,escapechar=\$,moredelim=**[is][\color{red}]{!}{!},}\lstset{#1}}{} Every enumeration in Java is an enumeration class. For a basic enumeration \begin{Java} enum Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; Weekday day = Weekday.Sat; \end{Java} the scoped enumerators are an ordered list of @final@ methods of type integer, ordered left to right starting at 0, increasing by 1. The value of an enumeration instance is restricted to the enumeration's enumerators. There is an implicit integer variable in the enumeration used to store the value of an enumeration instance. The position (ordinal) and label are accessible, and the value is the same as the position. \begin{Java} System.out.println( !day.ordinal()! + " " + !day! ); // 5 Sat \end{Java} There are no implicit conversions to/from an enumerator and its underlying type. To explicitly assign enumerator values, the enumeration must specify an explicit type in the enumeration class. \begin{Java} enum Weekday { Mon( -4 ), Tue( -3 ), Wed( -2 ), Thu( -1 ), Fri( 0 ), Sat( 1 ), Sun( 2 ); // must appear first private int day; $\C{// underlying enumeration type}$ private Weekday( int d ) { day = d; } $\C{// used to initialize enumerators and instances}$ }; Weekday day = Weekday.Sat; $\C{// implicit constructor call}$ \end{Java} The position, value, and label are accessible. \begin{Java} System.out.println( !day.ordinal()! + " " + !day.day! + " " + !day! ); // 5 1 Sat \end{Java} The constructor is private so only initialization or assignment can be used to set an enumeration, which ensures only corresponding enumerator values are allowed. Like \Csharp, \VRef[Figure]{f:JavaFreeVersusClass} shows the same example for an enumeration with free routines for manipulation, and embedding the enumeration and operations into an enumeration class. \begin{figure} \centering \lstDeleteShortInline@ \begin{tabular}{@{}l|l@{}} \multicolumn{1}{@{}c|}{non-object oriented} & \multicolumn{1}{c@{}}{object oriented} \\ \hline \begin{Java} public class test { enum Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; static boolean isWeekday( Weekday wd ) { return Weekday.Mon.ordinal() <= wd.ordinal() && wd.ordinal() <= Weekday.Fri.ordinal(); } static boolean isWeekend( Weekday wd ) { return Weekday.Sat.ordinal() <= wd.ordinal() && wd.ordinal() <= Weekday.Sun.ordinal(); } public static void main( String[] args ) { Weekday day = Weekday.Sat; System.out.println( isWeekday( day ) ); System.out.println( isWeekend( day ) ); } } \end{Java} & \begin{Java} public class test { public !enum! WeekDay { Mon(-4), Tue(-3), Wed(-2), Thu(-1), Fri(0), Sat(1), Sun(2); private int day; public boolean isWeekday() { return day <= 0; } public boolean isWeekend() { return day > 0; } private WeekDay( int d ) { day = d; } } public static void main( String[] args ) { WeekDay day = WeekDay.Sat; System.out.println( day.isWeekday() ); System.out.println( day.isWeekend() ); } } \end{Java} \end{tabular} \lstMakeShortInline@ \caption{Java: Free Routine Versus Class Enumeration} \label{f:JavaFreeVersusClass} \end{figure} An enumeration can appear in a @switch@ statement, but no ranges. \begin{Java} switch ( day ) { case Mon: case Tue: case Wed: case Thu: case Fri: System.out.println( "weekday" ); break; case Sat: case Sun: System.out.println( "weekend" ); break; } \end{Java} Looping over an enumeration is done using method @values@, which returns the array of enumerator values. \begin{Java} for ( Weekday iday : Weekday.values() ) { System.out.println( iday.ordinal() + " " + iday + " " ); } \end{Java} As well, Java provides an @EnumSet@ where the underlying type is an efficient set of bits, one per enumeration \see{\Csharp \lstinline{Flags}, \VRef{s:Csharp}}, providing (logical) operations on groups of enumerators. There is also a specialized version of @HashMap@ with enumerator keys, which has performance benefits. Enumeration inheritence is disallowed because an enumeration is @final@. \section{Modula-3} \section{Rust} \section{Swift} \lstnewenvironment{swift}[1][]{\lstset{language=Swift,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} Model custom types that define a list of possible values. An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type. Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages. You can define a common set of related cases as part of one enumeration, each of which has a different set of values of appropriate types associated with it. Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration's current value, and instance methods to provide functionality related to the values the enumeration represents. Enumerations can also define initializers to provide an initial case value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality. For more about these capabilities, see Properties, Methods, Initialization, Extensions, and Protocols. \paragraph{Enumeration Syntax} You introduce enumerations with the @enum@ keyword and place their entire definition within a pair of braces: \begin{swift} enum SomeEnumeration { // enumeration definition goes here } \end{swift} Here's an example for the four main points of a compass: \begin{swift} enum CompassPoint { case north case south case east case west } \end{swift} The values defined in an enumeration (such as @north@, @south@, @east@, and @west@) are its enumeration cases. You use the @case@ keyword to introduce new enumeration cases. Note: Swift enumeration cases don't have an integer value set by default, unlike languages like C and Objective-C. In the CompassPoint example above, @north@, @south@, @east@ and @west@ don't implicitly equal 0, 1, 2 and 3. Instead, the different enumeration cases are values in their own right, with an explicitly defined type of CompassPoint. Multiple cases can appear on a single line, separated by commas: \begin{swift} enum Planet { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } \end{swift} Each enumeration definition defines a new type. Like other types in Swift, their names (such as @CompassPoint@ and @Planet@) start with a capital letter. Give enumeration types singular rather than plural names, so that they read as self-evident: \begin{swift} var directionToHead = CompassPoint.west \end{swift} The type of @directionToHead@ is inferred when it's initialized with one of the possible values of @CompassPoint@. Once @directionToHead@ is declared as a @CompassPoint@, you can set it to a different @CompassPoint@ value using a shorter dot syntax: \begin{swift} directionToHead = .east \end{swift} The type of @directionToHead@ is already known, and so you can drop the type when setting its value. This makes for highly readable code when working with explicitly typed enumeration values. \paragraph{Matching Enumeration Values with a Switch Statement} You can match individual enumeration values with a switch statement: \begin{swift} directionToHead = .south switch directionToHead { case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") } // Prints "Watch out for penguins" \end{swift} You can read this code as: \begin{quote} "Consider the value of directionToHead. In the case where it equals @.north@, print "Lots of planets have a north". In the case where it equals @.south@, print "Watch out for penguins"." ...and so on. \end{quote} As described in Control Flow, a switch statement must be exhaustive when considering an enumeration's cases. If the case for @.west@ is omitted, this code doesn't compile, because it doesn't consider the complete list of @CompassPoint@ cases. Requiring exhaustiveness ensures that enumeration cases aren't accidentally omitted. When it isn't appropriate to provide a case for every enumeration case, you can provide a default case to cover any cases that aren't addressed explicitly: \begin{swift} let somePlanet = Planet.earth switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } // Prints "Mostly harmless" \end{swift} \paragraph{Iterating over Enumeration Cases} For some enumerations, it's useful to have a collection of all of that enumeration's cases. You enable this by writing @CaseIterable@ after the enumeration's name. Swift exposes a collection of all the cases as an allCases property of the enumeration type. Here's an example: \begin{swift} enum Beverage: CaseIterable { case coffee, tea, juice } let numberOfChoices = Beverage.allCases.count print("\(numberOfChoices) beverages available") // Prints "3 beverages available" \end{swift} In the example above, you write @Beverage.allCases@ to access a collection that contains all of the cases of the @Beverage@ enumeration. You can use @allCases@ like any other collection -- the collection's elements are instances of the enumeration type, so in this case they're Beverage values. The example above counts how many cases there are, and the example below uses a for-in loop to iterate over all the cases. \begin{swift} for beverage in Beverage.allCases { print(beverage) } // coffee // tea // juice \end{swift} The syntax used in the examples above marks the enumeration as conforming to the @CaseIterable@ protocol. For information about protocols, see Protocols. \paragraph{Associated Values} The examples in the previous section show how the cases of an enumeration are a defined (and typed) value in their own right. You can set a constant or variable to Planet.earth, and check for this value later. However, it's sometimes useful to be able to store values of other types alongside these case values. This additional information is called an associated value, and it varies each time you use that case as a value in your code. You can define Swift enumerations to store associated values of any given type, and the value types can be different for each case of the enumeration if needed. Enumerations similar to these are known as discriminated unions, tagged unions, or variants in other programming languages. For example, suppose an inventory tracking system needs to track products by two different types of barcode. Some products are labeled with 1D barcodes in UPC format, which uses the numbers 0 to 9. Each barcode has a number system digit, followed by five manufacturer code digits and five product code digits. These are followed by a check digit to verify that the code has been scanned correctly: Other products are labeled with 2D barcodes in QR code format, which can use any ISO 8859-1 character and can encode a string up to 2,953 characters long: It's convenient for an inventory tracking system to store UPC barcodes as a tuple of four integers, and QR code barcodes as a string of any length. In Swift, an enumeration to define product barcodes of either type might look like this: \begin{swift} enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } \end{swift} This can be read as: \begin{quote} "Define an enumeration type called Barcode, which can take either a value of upc with an associated value of type @(Int, Int, Int, Int)@, or a value of @qrCode@ with an associated value of type @String@." \end{quote} This definition doesn't provide any actual @Int@ or @String@ values -- it just defines the type of associated values that Barcode constants and variables can store when they're equal to @Barcode.upc@ or @Barcode.qrCode@. You can then create new barcodes using either type: \begin{swift} var productBarcode = Barcode.upc(8, 85909, 51226, 3) \end{swift} This example creates a new variable called @productBarcode@ and assigns it a value of @Barcode.upc@ with an associated tuple value of @(8, 85909, 51226, 3)@. You can assign the same product a different type of barcode: \begin{swift} productBarcode = .qrCode("ABCDEFGHIJKLMNOP") \end{swift} At this point, the original @Barcode.upc@ and its integer values are replaced by the new @Barcode.qrCode@ and its string value. Constants and variables of type Barcode can store either a @.upc@ or a @.qrCode@ (together with their associated values), but they can store only one of them at any given time. You can check the different barcode types using a switch statement, similar to the example in Matching Enumeration Values with a Switch Statement. This time, however, the associated values are extracted as part of the switch statement. You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case's body: \begin{swift} switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") case .qrCode(let productCode): print("QR code: \(productCode).") } // Prints "QR code: ABCDEFGHIJKLMNOP." \end{swift} If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single let or var annotation before the case name, for brevity: \begin{swift} switch productBarcode { case let .upc(numberSystem, manufacturer, product, check): print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") case let .qrCode(productCode): print("QR code: \(productCode).") } // Prints "QR code: ABCDEFGHIJKLMNOP." \end{swift} \paragraph{Raw Values} The barcode example in Associated Values shows how cases of an enumeration can declare that they store associated values of different types. As an alternative to associated values, enumeration cases can come prepopulated with default values (called raw values), which are all of the same type. Here's an example that stores raw ASCII values alongside named enumeration cases: \begin{swift} enum ASCIIControlCharacter: Character { case tab = "\t" case lineFeed = "\n" case carriageReturn = "\r" } \end{swift} Here, the raw values for an enumeration called ASCIIControlCharacter are defined to be of type Character, and are set to some of the more common ASCII control characters. Character values are described in Strings and Characters. Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration. Note Raw values are not the same as associated values. Raw values are set to prepopulated values when you first define the enumeration in your code, like the three ASCII codes above. The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so. Implicitly Assigned Raw Values When you're working with enumerations that store integer or string raw values, you don't have to explicitly assign a raw value for each case. When you don't, Swift automatically assigns the values for you. For example, when integers are used for raw values, the implicit value for each case is one more than the previous case. If the first case doesn't have a value set, its value is 0. The enumeration below is a refinement of the earlier Planet enumeration, with integer raw values to represent each planet's order from the sun: \begin{swift} enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } \end{swift} In the example above, Planet.mercury has an explicit raw value of 1, Planet.venus has an implicit raw value of 2, and so on. When strings are used for raw values, the implicit value for each case is the text of that case's name. The enumeration below is a refinement of the earlier CompassPoint enumeration, with string raw values to represent each direction's name: \begin{swift} enum CompassPoint: String { case north, south, east, west } \end{swift} In the example above, CompassPoint.south has an implicit raw value of "south", and so on. You access the raw value of an enumeration case with its rawValue property: \begin{swift} let earthsOrder = Planet.earth.rawValue // earthsOrder is 3 let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west" \end{swift} \paragraph{Initializing from a Raw Value} If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value's type (as a parameter called rawValue) and returns either an enumeration case or nil. You can use this initializer to try to create a new instance of the enumeration. This example identifies Uranus from its raw value of 7: \begin{swift} let possiblePlanet = Planet(rawValue: 7) // possiblePlanet is of type Planet? and equals Planet.uranus \end{swift} Not all possible Int values will find a matching planet, however. Because of this, the raw value initializer always returns an optional enumeration case. In the example above, possiblePlanet is of type Planet?, or "optional Planet." Note The raw value initializer is a failable initializer, because not every raw value will return an enumeration case. For more information, see Failable Initializers. If you try to find a planet with a position of 11, the optional Planet value returned by the raw value initializer will be nil: \begin{swift} let positionToFind = 11 if let somePlanet = Planet(rawValue: positionToFind) { switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } } else { print("There isn't a planet at position \(positionToFind)") } // Prints "There isn't a planet at position 11" \end{swift} This example uses optional binding to try to access a planet with a raw value of 11. The statement if let somePlanet = Planet(rawValue: 11) creates an optional Planet, and sets somePlanet to the value of that optional Planet if it can be retrieved. In this case, it isn't possible to retrieve a planet with a position of 11, and so the else branch is executed instead. \paragraph{Recursive Enumerations} A recursive enumeration is an enumeration that has another instance of the enumeration as the associated value for one or more of the enumeration cases. You indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to insert the necessary layer of indirection. For example, here is an enumeration that stores simple arithmetic expressions: \begin{swift} enum ArithmeticExpression { case number(Int) indirect case addition(ArithmeticExpression, ArithmeticExpression) indirect case multiplication(ArithmeticExpression, ArithmeticExpression) } \end{swift} You can also write indirect before the beginning of the enumeration to enable indirection for all of the enumeration's cases that have an associated value: \begin{swift} indirect enum ArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplication(ArithmeticExpression, ArithmeticExpression) } \end{swift} This enumeration can store three kinds of arithmetic expressions: a plain number, the addition of two expressions, and the multiplication of two expressions. The addition and multiplication cases have associated values that are also arithmetic expressions -- these associated values make it possible to nest expressions. For example, the expression (5 + 4) * 2 has a number on the right-hand side of the multiplication and another expression on the left-hand side of the multiplication. Because the data is nested, the enumeration used to store the data also needs to support nesting -- this means the enumeration needs to be recursive. The code below shows the ArithmeticExpression recursive enumeration being created for (5 + 4) * 2: \begin{swift} let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2)) \end{swift} A recursive function is a straightforward way to work with data that has a recursive structure. For example, here's a function that evaluates an arithmetic expression: \begin{swift} func evaluate(_ expression: ArithmeticExpression) -> Int { switch expression { case let .number(value): return value case let .addition(left, right): return evaluate(left) + evaluate(right) case let .multiplication(left, right): return evaluate(left) * evaluate(right) } } print(evaluate(product)) // Prints "18" \end{swift} This function evaluates a plain number by simply returning the associated value. It evaluates an addition or multiplication by evaluating the expression on the left-hand side, evaluating the expression on the right-hand side, and then adding them or multiplying them. \section{Python} \section{Algebraic Data Type}