Swift Learning Swift Programming Tour---enumeration (12)

Source: Internet
Author: User
Tags control characters uppercase letter

  Enumerations define a common type for a set of related values, and allow you to use these values in a type-safe manner in your code, in Swift, where the enumeration type is a first-class (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.

  

  Enumeration syntax

Use the ENUM keyword to declare an enumeration type and place the entire definition inside curly braces.

enum someeumeration {     //

Here is an example of a compass in 4 main directions

enum        compasspoint.             East     case  West}

The values defined in the enumeration (for example, North,south,east and West) are the member values (or members) of the enumeration. The case keyword declares 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 members can appear on the same line, separated by commas

enum Planet {     case

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.

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:

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.

  Using switch to match enumeration values

Match a single enumeration value

Directiontohead = . SouthSwitchDirectiontohead { Case . North:println ("Lots of Planets has a north")  Case . South:println ("Watch out for Penguins")  Case . East:println ("Where The sun rises")  Case . West:println ("Where The skies is blue") } //Prints "Watch out for Penguins"

A switch statement must be comprehensive. 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

Let someplanet =switch case . Earth:     println ("Mostly harmless"default:     println ("nota safe place for humans"//

  Associated value

Swift's enumeration can store any type of association value, and each member's data type can be different. 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 codes to track goods. Some products are labeled with the UPC-A format barcode, which uses numbers 0 through 9. Each bar code has a number that represents the "digital system" followed by 10 digits representing the "identifier". The last number is the "check" bit to verify that the code is scanned correctly:

Other products are labeled QR code format, it can use any iso8859-1 characters, and can encode a maximum of 2,953 characters of the string:

For the inventory tracking system, it is convenient to store the UPC-A code as a tuple of three integer values, and the QR code as a string of any length.

In Swift, the enumeration used to define the barcode of two commodities

enum Barcode {     case  UPCA (int, int, int.)     Case

You can then create a new barcode using any one of the barcode types

var productbarcode = BARCODE.UPCA (83)

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,

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.

Enumerate switch statements

Switch case . UPCA (Let-numbersystem, let-identifier, let-check):     println ("upc-a with value of \ (Numbersystem), \ (identifier), \ (check). "   case . QRCode (Let ProductCode):     println ("QR Code with value of \ (ProductCode). " //

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

Switch case let . UPCA (Numbersystem, identifier, check):     println ("upc-a with value of \ (Numbersystem), \ ( identifier), \ (check). "   case let . QRCode (ProductCode):     println ("QR Code with value of \ (ProductCode). " //

  Raw Values

An enumeration member can have an initial value, where these initial values have the same type, and the following is an example of an enumeration member storing the original ASCII value

enum Asciicontrolcharacter:character {     case"\ t"      case " \ n "      Case " \ r "
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 enumeration of polygons is a refinement of the previous planet enumeration, using the original integer values to represent the order of each planet in the solar system
enum Planet:int {     case1

Auto-increment means that the original value of Planet.venus is 2, and so on. The initial value of the enumeration member can be accessed using the Toraw method of the enumeration member
Let Earthsorder =//

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

Let possibleplanet = Planet.fromraw (7//

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:

Let Positiontofind =9 ifLet someplanet =Planet.fromraw (positiontofind) {Switchsomeplanet { Case . Earth:println ("Mostly Harmless")     default: println ("Not a safe place for humans")     } } Else{println ("there isn ' t a planet at position \ (positiontofind)") } //prints "There isn ' t a planet at position 9

This example uses an optional binding (optional binding) to attempt to access a planet by an initial value of 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.

Swift Learning Swift Programming Tour---enumeration (12)

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.