Swift Learning-09--Enumeration

Source: Internet
Author: User

Recursive enumeration

Beauty Home defines a common type for a set of related values that you can use in your code in a type-safe manner.

If you're familiar with C, you'll know that in C, enumerations assign associated names to a set of integer values, and the enumerations in Swift are more flexible and do not have to provide a value to each enumeration member, and if the enumeration member is given a value (called the original value), the type of the value can be a string, a character, Or an integer value or a floating-point number,

In addition, enumeration members can specify that any type of association value is stored in an enumeration member, and you can define a set of related enumeration members in an enumeration, each of which can have an appropriate type of associated value.

Enumeration syntax

Use the enum keyword to create enumerations and place their whole definitions inside a bunch of curly braces

Enum someenumeration{

Enumeration definitions are placed here

}

The following example of the Compass Four directions is represented by an enumeration

Enum CompassPoint {

Case North

Case South

Case East

Case West

}

The values defined in the enumeration (such as North, south, east, west) are the member values (or members) of this enumeration, and you can use the Case keyword to define a new enumeration member value

Note: Unlike C and OC, Swift's enumeration members are not assigned a default integer value when they are created, in the CompassPoint example above, north, south, east and west are not implicitly assigned to 0,1,2,3, instead, These enumeration members themselves are complete values, and the types of these values are already well-defined CompassPoint types

Multiple members can appear on the same line, separated by commas

Enum Planet {

Case Mercuty, Venus,earth, Jupiter, Saturn, Uranus, Neptune

}

Each enumeration defines a completely new type, like other types in Swift, whose name should start with a large letter, give the enumeration type a single-digit name instead of a plural name, so that it is easier to read.

var directiontohead = Compasspoint.west

The type of directiontohead can be inferred when it is initialized by a value of CompassPoint, and once Directiontohead is declared as a compasspoint type, you can set it to another Comp using a shorter point syntax The value of the Asspoint,

Directiontohead =. East

When the type of directiontohead is known, it is again assigned a value to omit the enumeration type name, which makes the code more readable when using an enumeration value with an explicit type

Using Swift statements to match enumeration values

You can use Swift statements to match a single value:

Directiontohead =. South

Switch Directiontohead {

Case-North:

Print ("Lots of Planets has a North")

Case-South:

Print ("Watch out for Penguins")

Case. East:

Print ("Where The Sun Rises")

Case West:

Print ("Where The Skies is Blue")

Default

Print ("None")

}

When judging the value of an enumeration type, the Swift statement must be exhaustive, and when it is not necessary to match each enumeration member, you can provide a default branch to cover all the non-explicitly handled enumeration members

Let someplanet = Planet.earth

Switch Someplanet {

Case. Earth:

Print ("Mostly harmless")

Default

Print ("Not a safe place for humans")

}

Associated value

Sometimes it can be more useful to store other types of association values together with member values, which allows you to store additional custom information along with member values, and you can modify this association value each time you use the enumeration member in your code.

You can define Swift enumerations to store any type of association value, and if necessary, the associated value type for each enumeration member can be the same as each part, and this attribute of the enumeration is similar to a recognizable union in other languages, a label union, or a variant.

For example: Suppose an inventory tracking system needs to use different types of barcodes to track goods, there are four numbers, other products labeled QR code format, it is possible to use any character string

In Swift, an enumeration that represents two commodity barcodes is defined using the following method

Enum barcode{

Case UPC (Int,int,int,int)

Case QRCode (String)

}

The above can be understood as: "Defines an enumeration type named BarCode, a member of which is a UPC with an associated value of type (int, int, int, int), and another member is a qrcode with the associated value of String type"

This definition does not provide any Int or String associated values, it simply defines the types of associated values that can be stored when BarCode constants and variables are equal to BARCODE.UPC or Barcode.qrcode

You can then create a new barcode using any one of the barcode types, for example:

var productbarcode = BARCODE.UPC (8, 85909, 51226, 3)

The example above creates a variable named Productbarcode and assigns the BARCODE.UPC to it.

The same product can be assigned a different type of barcode, for example:

Productbarcode =. QRCode ("Bjuibhyugvutyfvfy")

At this point, the original BARCODE.UPC and its integer association values are replaced by the new Barcode.qrcode and their string association values, and the constants and variables of the Barcode type can store one. UPC or A. QRCode, (along with their associated values), but at the same time Only one of two values can be stored

As before, you can use a switch statement to check the different barcode types. This time, however, the correlation 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:

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).")

}

Print "QR Code:abcdefghijklmnop."

If all the associated values of an enumeration member are extracted as constants, or are extracted as variables, for brevity, you can simply label a let or Var before the member name:

Switch Productbarcode {

Case let. UPC (Numbersystem, manufacturer, product, check):

Print ("UPC: \ (numbersystem), \ (manufacturer), \ (product), \ (check).")

Case let. QRCode (ProductCode):

Print ("QR code: \ (ProductCode).")

}

Output "QR Code:abcdefghijklmnop."

Original value

In the previous example, it was demonstrated how to declare an enumeration member that stores different types of associated values as an alternative to the associated values, which can be pre-populated by default values (called raw values) that must be of the same type

The original value can be a string, a character, or an arbitrary integer or float, and each original value must be unique within the enumeration declaration.

Note: The original value and the associated value are different, the original value is in the definition enumeration is a pre-populated value, for a specific enumeration member, its original value is always the same, the associated value is to create a variable based on an enumeration member or a constant is a value set, the association value of the enumeration member can vary

Implicit assignment of the original value

You do not need to explicitly set the original value for each enumeration member when using an enumeration of the original value as an integer or string type, and Swift will automatically assign you a value

For example, when an integer is used as the original value, the value of the implicitly assigned value increments by 1, and if the first enumeration member does not set the original value, its original value will be 0

Enum Planet2:int {

Case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune

}

In the example above, the explicit original value of Plant.mercury is 1,planet.venus's implicit original value is 2, and so on.

When a string is used as the original value of an enumeration type, the implicit original value of each enumeration member is the name of the enumeration member.

The following example is the refinement of the CompassPoint enumeration, which uses the original value of the string type to represent the names of each direction:

Enum Compasspoint2:string {

Case North, south, east, west

}

In the example above, Compasspoint2.south has an implicit primitive value South, and so on

The original value of the enumeration member can be accessed using the RawValue property of the enumeration member

Let Earthsorder = Planet2.earth.rawValue

Let sunsetdirection = CompassPoint2.west.rawValue

Initializing an enumeration instance with raw values

If the original value is used when defining an enumeration type, an initialization method is automatically obtained, which receives a parameter called RawValue, which is the original value type, the type of the original value, the return value is an enumeration member or nil, You can use this initialization method to create a new enumeration instance

This example creates a new enumeration member Uranus with the original value 7:

Let possibleplanet = Planet2 (rawvalue:7)

However, not all Int values can find a matching enumeration member, so the original value constructor always returns an optional enumeration member, in the example above, Possibleplanet is Planet2? Type, or ' optional Planet2 '

Note: The original value constructor is a failed constructor, because not every original value has an enumeration member corresponding to it

If you are trying to find an enumeration member with a position of 11, returning an optional Planet2 value from the original value constructor will be nil

Recursive enumeration

A recursive enumeration is an enumeration type that has one or more enumeration members that use an instance of the enumeration type as the associated value, and when using a recursive enumeration, the editor inserts an indirection layer that you can precede the enumeration member with indirect to indicate that the member is recursive

For example, in the following example, an enumeration type stores a simple arithmetic expression

Enum Arithmeticexpression {

Case Number (INT)

Indirect case addition (arithmeticexpression, arithmeticexpression)

Indirect case multiplication (arithmeticexpression,arithmeticexpression)

}

You can also add the indirect keyword at the beginning of the enumeration type to indicate that all its members are recursive

Indirect enum ArithmeticExpression2 {

Case Number (INT)

case addition (Arithmeticexpression, arithmeticexpression)

Case multiplication (arithmeticexpression, arithmeticexpression)

}

The enumerated types defined above can store three arithmetic expressions: a pure number, a total of two expressions, and a two-expression multiplication. The associated values of enumeration members addition and multiplication are also arithmetic expressions-these associated values make it possible to nest expressions. For example, the expression (5 + 4) * 2, multiplication sign to the right is a number, and the left is another expression. Because the data is nested, the enumeration type used to store the data also needs to support this nesting-meaning that the enumeration type needs to support recursion. The following code shows the creation of an expression using the recursive enumeration of Arithmeticexpression (5 + 4) * 2

Let five = Arithmeticexpression.number (5)

Let four = Arithmeticexpression.number (4)

Let sum = Arithmeticexpression.addition (five, four)

Let Product = Arithmeticexpression.multiplication (sum, Arithmeticexpression.number (2))

Swift Learning-09--Enumeration

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.