The SWIFT programming language-official course translation Swift (9) enumeration----enumerations

Source: Internet
Author: User
Tags control characters uppercase letter



enumerations Define a set of related values for a common type, so that you can use them in a safe way in your code.


If you are familiar with the C language, you will know that in C the enumeration specifies the correlation name as a set of integer values. The enumerations in Swift are more flexible and do not have to provide a value for each enumeration member (enumeration member). If a value (considered "raw" value) is provided to each enumeration member, the value can be a string, a character, or an integer value or a floating-point value. In addition, enumeration members can specify that any type of association value is stored in an enumeration member value, just like a union (unions) and variant (variants) in other languages. You can define a common set of related members as part of an enumeration, each with a different set of values of the appropriate type associated with it. In Swift, the enumeration type is a-first-class type. They employ a number of features that have traditionally been supported only by classes, such as computed attributes (computed properties), which provide additional information about enumerating the current values, an instance method (instance methods), which provides the functionality associated with enumerating the values represented. Enumerations can also define constructors (initializers) to provide an initial member value, extend their functionality on the basis of the original implementation, and can comply with the Protocol (protocols) to provide standard functionality. For more relevant features, refer to properties, methods, construction procedures, extensions, and protocols. enumeration Syntax (enumeration Syntax)Use the enum keyword and place their entire definition in a pair of curly braces:
 
 
1 enum SomeEumeration { 
2     // enumeration definition goes here 
3 } 
Here is an example of a compass in four directions:
 
1 enum CompassPoint { 
2     case North 
3     case South 
4     case East 
5     case West 
6 } 
The values defined in an enumeration (for example, North,south,east and West) are the member values (or members) of the enumeration. The case keyword indicates that the new row member value will be defined.Note: Unlike C and Objective-c, Swift's enumeration members are not assigned a default integer value when they are created. In the compasspoints example above, North,south,east and West are not implicitly equal to 0,1,2 and 3. Instead, these different enumeration members have their own different values in a display definition of compasspoint. Multiple member values can appear on the same line, separated by commas:
 
1 enum Planet { 
2     case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Nepturn 
3 } 
Each enumeration defines a completely new type. Like other types in Swift, their names (such as CompassPoint and planet) must start with an uppercase letter. A single-digit name instead of a plural name for an enumeration type to make it easier to read:
 
1 var directionToHead = CompassPoint.West 
The type of directiontohead is inferred when it is initialized by a possible value of compasspoint. Once Directiontohead is declared as a compasspoint, you can use the shorter point (.) syntax to set it to the value of another compasspoint:
1 directionToHead = .East  
When the type of Directiontohead is known, you can no longer write the type name when you set its value. Using enumeration values of display types can make your code more readable. Match enumeration values and Switch statements (Matching enumeration values with a switch Statement)You can match a single enumeration value with a switch statement:
 
 1 directionToHead = .South 
 2 switch directionToHead { 
 3 case .North: 
 4     println("Lots of planets have a north") 
 5 case .South: 
 6     println("Watch out for penguins") 
 7 case .East: 
 8     println("Where the sun rises") 
 9 case .West: 
10     println("Where the skies are blue") 
11 } 


You can understand this code this way:


"Consider the value of Directiontohead. When it equals. North, print "Lots of Planets has a north". When it equals. South, print "Watch out for Penguins". "And so on. As described in the control flow, a switch statement must be comprehensive when considering the members of an enumeration. If it is ignored. West this case, the above code will not be compiled, because it does not take into account all the members of CompassPoint. The requirement of comprehensiveness ensures that enumeration members are not accidentally omitted. When you do not need to match each enumeration member, you can provide a default branch to cover any member that is not explicitly raised:
 
 
1 let somePlanet = Planet.Earth 
2 switch somePlanet { 
3 case .Earth: 
4     println("Mostly harmless") 
5 default: 
6     println("Not a safe place for humans") 
7 } 
8 // prints "Mostly harmless” 




Association value (associated values)The example in the previous section shows how a member of an enumeration is defined (categorized). You can set a constant or variable for Planet.earth, and then look at the value later. However, it can sometimes be useful if you can store other types of association values together with member values. This allows you to store additional custom information along with the member values and allow this information to change every time you use the member in your code.   You can define Swift's enumeration to store any type of association value, and the data type of each member can be different if required. This attribute of the enumeration is similar to the recognizable union (discriminated unions) in other languages, the label union (tagged unions), or the variant (variants).   For example, suppose an inventory tracking system needs to use two different types of barcodes to track goods. Some products are labeled with the UPC-A format, which uses numbers 0 through 9. Each barcode has a number that represents the "digital system" followed by 10 digits representing the "identifier". The last number is the "check" bit, which verifies that the code is scanned correctly: QR code on other goods, it can use any iso8859-1 character, and can encode a string of up to 2,953 characters:   for the inventory tracking system, It is convenient to store the UPC-A code as a tuple of three integer values, and to save the QR code as a string of any length.   In Swift, the enumeration used to define the two commodity barcodes is this:
 
1 enum Barcode { 
2     case UPCA(Int, Int, Int) 
3     case QRCode(String) 
4 } 
The code above can be understood as: "Defines an enumeration type named barcode, which can be an association value (int,int,int) for UPCA, or a string-type (string) associated value of QRCode. "This definition does not provide the actual value of any int or string, it simply defines the type of the associated value when the barcode constant and the variable are equal to BARCODE.UPCA or Barcode.qrcode." You can then use any one of the barcode types to create new barcodes, such as:
1 
var productBarcode = Barcode.UPCA(8, 85909_51226, 3) 
The above example creates a new variable named Productbarcode and assigns it a BARCODE.UPCA associated tuple value (8, 8590951226, 3). The provided identifier value has an underscore in the integer number, making it easy to read barcodes. The same product can be assigned to a different type of barcode, such as:
 
1 productBarcode = .QRCode("ABCDEFGHIJKLMNOP") 
At this point, the original BARCODE.UPCA and its integer value are replaced by the new Barcode.qrcode and its string values. The constant and variable of a barcode can be stored in a single. UPCA or A. QRCode (along with its associated values), but only one of them can be stored at any given time. As before, different barcode types can be checked using a switch statement, but this time the association value can be extracted as part of the switch statement. You can extract each associated value as a constant (with a let prefix) or as a variable (prefixed with Var) in the case branch code of switch:
 
 
1 switch productBarcode { 
2 case .UPCA(let numberSystem, let identifier, let check): 
3     println("UPC-A with value of \(numberSystem), \(identifier), \(check).") 
4 case .QRCode(let productCode): 
5     println("QR code with value of \(productCode).") 
6 } 
7 // prints "QR code with value of ABCDEFGHIJKLMNOP.” 
If all the associated values of an enumeration member are extracted as constants, or they are all extracted as variables, for brevity, you can just place a var or let label in front of the member name:
 
1 switch productBarcode { 
2 case let .UPCA(numberSystem, identifier, check): 
3     println("UPC-A with value of \(numberSystem), \(identifier), \(check).") 
4 case let .QRCode(productCode): 
5     println("QR code with value of \(productCode).") 
6 } 
7 // prints "QR code with value of ABCDEFGHIJKLMNOP." 
  original value (raw values)The bar code example in the association Values section demonstrates how a member of an enumeration declares that they store different types of associated values. As an alternative to associated values, enumeration members can be prepopulated by default values (known as raw values), where the original values have the same type. Here is an example of an enumeration member storing raw ASCII values:
 
1 enum ASCIIControlCharacter: Character { 
2     case Tab = "\t" 
3     case LineFeed = "\n" 
4     case CarriageReturn = "\r" 
5 } 
Here, the original value type of the enumeration called Asciicontrolcharacter is defined as the character type character, and some of the more common ASCII control characters are set. For a description of the character value, see the string and character chapters.Note that the original value and the associated value are not the same. When you start defining enumerations in your code, the original values are pre-populated values like the above three ASCII codes. For a particular enumeration member, its original value is always the same. The associated value is set when you create a new constant or variable based on an enumeration member, and each time you do so, its value can be different. The original value can be a string, a character, or any integral or floating-point value. Each original value must be unique within its enumeration declaration. When an integer value is used for the original value, the other enumeration members are automatically incremented if they do not have a value. The following enumeration is a refinement of the previous planet enumeration, using the original integer values to represent the order of each planet in the solar system:
 
1 enum Planet: Int { 
2     case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune 
3 } 
Auto-increment means that the original value of Planet.venus is 2, and so on. The original value of the enumeration member can be accessed using the Toraw method of the enumeration member:
 
1 let earthsOrder = Planet.Earth.toRaw() 
2 // earthsOrder is 3 


Use the Fromraw method of the enumeration to try to find an enumeration member with a specific original value. This example identifies Uranus by the original value 7:


 
1 let possiblePlanet = Planet.fromRaw(7) 
2 // possiblePlanet is of type Planet? and equals Planet.Uranus 


However, not all possible int values can be found for a matching planet. Because of this, the Fromraw method can return an optional enumeration member. In the example above, Possibleplanet is the planet type, or "optional planet".


If you are trying to find a planet with a position of 9, the optional planet value returned by Fromraw will be nil:
 
 1 let positionToFind = 9 
 2 if let somePlanet = Planet.fromRaw(positionToFind) { 
 3     switch somePlanet { 
 4     case .Earth: 
 5         println("Mostly harmless") 
 6     default: 
 7         println("Not a safe place for humans") 
 8     } 
 9 } else { 
10     println("There isn‘t a planet at position \(positionToFind)") 
11 } 
12 // prints "There isn‘t a planet at position 9

This example uses an optional binding (optional binding), which attempts to access a planet through the original value 9. If Let someplanet = Planet.fromraw (9) statement obtains an optional Planet, if optional Planet can be obtained, the someplanet is set to the content of the optional Planet. In this example, a planet with a position of 9 cannot be retrieved, so the Else branch is executed.


The SWIFT programming language-official course translation Swift (9) enumeration----enumerations


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.