A detailed enumeration of the Swift tutorials _swift

Source: Internet
Author: User
Tags control characters

Enumerations define a common set of data with dependencies and use them in a safe way in your code.

If you are familiar with the C language, you will know that the enumeration in C language specifies that the correlation name is a set of integer values. Enumerations are more flexible in swift and do not have to provide a value for each member of the enumeration. If a value (called the "original" value) is supplied to each enumeration member, the value can be a string, a character, or any value of an integer or floating-point type.

In addition, an enumeration member can specify any type, and each member can store different related values, like using a collection or variant in other languages. You can also define a common set of related members as an enumeration, each with a different set of values of the appropriate type associated with it.

Enumerating types is the most important type in Swift. It employs many features that were previously only available to classes, such as computational performance, to provide more information about the current value of the enumeration, and the values traditionally supported by the enumeration representations of methods and instance methods. Enumerations can also define initialization to provide an initial member value, expand their functionality on the original basis, and use protocols to provide standard functionality.

For more information on these features, see Properties, Methods, initialization, Extensions, protocols

1. Enumeration syntax

Use enumerated enum keywords and put their entire definition within a pair of curly braces:

Copy Code code as follows:

Enum Someenumeration {
Enumeration definition goes here
}

Here is an example of a four-point compass:

Copy Code code as follows:

Enum CompassPoint {
Case North
Case South
Case East
Case West
}

Values defined in the enumeration, such as North,south,east and West, are member values (or members) of the enumeration. In this example the case keyword denotes a member value a new branch will be defined.

Note

Unlike C and Objective-c,swift enumeration members do not assign default integer values when they are created. In the above example compasspoints north,south,eath,west is not equal to the implied 0,1,2 and 3, but a value that is distinct from the type explicitly defined by CompassPoint.

The values of multiple members can appear on one line, separated by commas:

Copy Code code as follows:

Enum Planet {
Case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

A completely new type is defined in each enumeration definition. Like other swift types, their names (such as CompassPoint and planet) should be uppercase. Giving the name of an enumeration type singular instead of a plural is easier to understand, such as:

Copy Code code as follows:

var directiontohead = Compasspoint.west

An inference that is initialized with a possible value of compasspoint when using the type of directiontohead. Once Directiontohead is declared as a compasspoint, you can set it to use a shorter. Syntax without having to write the enumeration CompassPoint value itself:

Copy Code code as follows:

Directiontohead =. East

The type of the directiontohead is known, so you can set its value without writing that type. Use type-specific enumeration values to make your code more readable.

2, matching enumeration values and switch statements

You can use a single enumeration value to match a switch statement:

Copy Code code as follows:

Directiontohead =. South
Switch Directiontohead {
Case. North:
println ("Lots of Planets have a North")
Case. South:
println ("Watch Out for Penguins")
Case. East:
println ("Where The Sun Rises")
Case. West:
println ("Where The Skies are Blue")
}
Prints "Watch out for Penguins"

You can understand this code:

"Consider the value of Directiontohead." When it equals North, print "Lots of planets have a north". When it equals South, print "Watch out for Penguins" and so on.

As the control flow describes, the switch statement considers the members of the enumeration, and if West is omitted, the code cannot be compiled because it does not consider the integrity of the CompassPoint member. The switch statement requires comprehensiveness to ensure that enumeration members are avoided accidentally omitting the occurrence.

When it does not need to match for each of the enumeration members, you can provide a default branch to cover any members that are not explicitly mentioned:

Copy Code code as follows:

Let someplanet = Planet.earth
Switch Someplanet {
Case. Earth:
println ("Mostly harmless")
Default
println ("Not a safe place for humans")
}
Prints "Mostly harmless"

3, correlation value

The example in the previous section delays how a member of an enumeration is defined (sorted). You can set a constant or variable for Planet.earth, and then check the value in your code. However, it is sometimes useful to store other types of association values in addition to the values of those members. This allows you to store additional custom information along with the member values and allow this information to be used in your code.

Swift's enumeration types can be made up of data types, which can be different if needed. This attribute of enumeration is similar to that of singular sets, tag sets, or variants in other languages.

For example, suppose an inventory tracking system requires two different types of barcodes to track the product. Some products are labeled UPC-A code format, it uses the number 0 to 9 of the one-dimensional barcode, each bar code has a "digital system" number, followed by the ten "identifier" number. The last one is the "check" bit to verify that the code has been scanned correctly:

Other products are posted in two-dimensional barcode QR code format, it can use any iso8859-1 characters, and can encode strings, up to 2,953 characters:

It will be convenient for the inventory tracking system to store the Upc-a barcode as a tuple of three integers, and the QR Code of the barcode for any length of the string.

You can use an enumeration in Swift to define two types of product barcodes, which can be structured like this:

Copy Code code as follows:

Enum Barcode {
Case UPCA (int, int, int)
Case QRCode (String)
}

This can be understood as:

"Defines a barcode enumeration type, which can be an association value (int,int,int) of any value type of UPC-A, or an association value of type string for QRCode. ”

This definition does not provide any actual int or string values, it simply defines the storage form of the barcode constants and variables when they are equal to the type of the BARCODE.UPCA or Barcode.qrcode associated value.

You can then use any of the types to create a new barcode:

Copy Code code as follows:

var productbarcode = BARCODE.UPCA (8, 85909_51226, 3)

This example creates a new variable named Productbarcode and assigns it a BARCODE.UPCA value (8,8590951226,3) to the associated tuple value. The supplied identifier value has an integer underlined text that 85909_51226 the barcode to make it easier to read.

Different types of barcodes can be assigned to the same product:

Copy Code code as follows:

Productbarcode =. QRCode ("Abcdefghijklmnop")

At this point, the original BARCODE.UPCA and its integer values are replaced by the new Barcode.qrcode and their string values. _ Bar code constants and variables can store any one _UPCA or QRCode (along with its associated values), but they can only store one of them at any given time.

Different barcode types can be checked with a switch statement as before, but this time the associated value can be extracted as part of the switch statement. If you extract each correlation value as a constant (let prefix) or variable (var prefix), use it within the case code of the switch statement:

Copy Code code as follows:

Switch Productbarcode {
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).")
}
Prints "QR code with value of Abcdefghijklmnop."

If all the enumeration member's association values are extracted as constants, or when all are extracted as variables, for brevity, you can place a Var, or a let callout in front of the member name:

Copy Code code as follows:

Switch Productbarcode {
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).")
}
Prints "QR code with value of Abcdefghijklmnop."

4. Original value

An example of a barcode in the associated value shows how a member of an enumeration can declare that they store different types of association values. As an alternative association value, an enumeration member can take out a pre-filled default value, called the original value, to have the same type.

Here is an example of storing the original ASCII value named enumeration member:

Copy Code code as follows:

Enum Asciicontrolcharacter:character {
Case Tab = "\ T"
Case linefeed = "\ n"
Case Carriagereturn = "\ r"
}

Here, the original value is defined as an enumeration of character types called Asciicontrolcharacter, and some of the more common ASCII control characters are set. A description of the character value's string and character.

Note that the original value is not the same as the associated value. When the original value is set to a pre-populated value, you should first define the enumeration in your code, like the three ASCII codes above. The original values for a particular enumeration member are always the same. When you create an association value setting based on a new member of an enumerated constant or variable, you can be different each time you do so.

The original value can be a string, a character, or any integer or floating-point type. Each original value must be declared uniquely in its enumeration. When integers are used for the original values, they are automatically incremented if the other enumeration members do not have a value.

The following is a detailed, early planet enumeration that uses the original integer value to represent the order of the solar system for each planet:

Copy Code code as follows:

Enum Planet:int {
Case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

Automatic increment means that the Planet.venus has a 2 original value, and so on.

To access the original value of its Toraw method enumeration member:

Copy Code code as follows:

Let Earthsorder = Planet.Earth.toRaw ()
Earthsorder is 3

Use the Fromraw method of the enumeration to attempt to find a particular original value enumeration member. This example identifies the location of the Uranus through the original value of 7:

Copy Code code as follows:

Let possibleplanet = Planet.fromraw (7)
Possibleplanet is of type Planet? and equals Planet.uranus

However, not all possible int values will find a matching planet. For this reason, the Fromraw method returns an optional enumeration member. In the example above, is the possibleplanet type planet? or "optional Planet".

If you try to find a position of Planet 9, returning the optional planet value via Fromraw will be none:

Copy Code code as follows:

Let Positiontofind = 9
If Let someplanet = Planet.fromraw (positiontofind) {
Switch Someplanet {
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 someplanet= Planet.fromraw (9) To try to access the optional collection Planet, set the search condition Someplanet in the optional Planet collection, and cannot retrieve a planet of 9 if the original value is 9. All else branches are executed.

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.