Enumerations)
EnumerationDefines a common group type for the values associated with a series, and allows you to use these values in case of type security during programming. If you are familiar with the C language, you must know thatEnumerationType is a series of integer values with the specified associated name. However, in swiftEnumerationType is more flexible, and you do not have to giveEnumerationType. If you provide a value (assuming the value is raw) to allEnumerationType member, the value can be a string, a character, an integer, or a floating point number,EnumerationThe members in can be specifically specified as any types that can be stored different from other Members, just like the Union or variation in other languages. You can define some associated members as a public setEnumerationEach part has a different set type and uses the appropriate type.
Enumeration syntax
You can start with Enum and use braces to include the entire definition body to define an enumeration:
Enum someenumeration {// defines enumeration here}
Here is an example that defines a compass with four directions:
enum CompassPoint { case North case South case East case West}
EnumerationVariables defined inNorth,South,East,West) YesEnumerationKeyword case is used to indicate that this line will define a new member variable
Note:
Unlike C or objective-C, in swiftEnumerationWhen a member of the type is initial, It is not assigned an integer by default.CompassPointIn this example,North,South,East,WestBy default, it is not implicitly equal to 0, 1, 2, and 3. Instead, they are different.EnumerationYou can control the type of the member to be used and the value to be assigned. You can define the compasspointEnumeration.
Multiple members can also be defined by a single row. They are separated by commas:
enum Plant{ case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}
Each enumeration definition defines a brand new type, just like other types in swfit, the enumeration name (like the aboveCompassPoint,PlantShould begin with an uppercase letter, so that they are singular type rather than plural type, so that they can be self-evident:
var directionToHead = CompassPoint.West
WhendirectionToHeadThe value is assignedCompassPointWhen a possible value in, its type can be inferred. OncedirectionToHeadDeclared as YesCompassPointType, you can use a comma expression to assign a value to anotherCompassPointThe value is:
directionToHead = .East
directionToHeadIs known, so you can ignore its type to assign a value to it. This makes the code highly readable when the enumeration value of the display type is used.
Use the switch statement to match the enumerated values
You can use the switch statement to access a single enumerated value:
Directiontohead =. southswitch 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")} // output "Watch out for penguins"
You can read this Code as follows:
ConsiderationsdirectionToHeadIf it is equal.NorthOutput "lost of planets have a north", if it is equal.SouthThe output is "Watch out for penguins ".
As mentioned in the control process chapter, when a switch statement is used to judge an enumeration value, it must include all enumeration members. Hypothesis.WestIf it is ignored, compilation errors will occur because it does not take into account all enumeration members. We need to make sure that all enumeration members are not ignored.
If it is not appropriate to consider the members of each enumeration, you can provide a default to cover other members not explicitly processed:
Let someplanet = planet. earthswitch someplanet {case. Earth: println ("mostly harmless") Default: println ("not a safe place for humans")} // output "mostly harmless"Associated Value
The example in the previous section shows how an enumeration member defines (and type) its own rights. You can set the value of a constant or variablePlanet.EarthAnd then check the value. However, it makes sense to store other types of associated values while retaining the Member values. This allows you to store additional custom information while saving Member values, and allows you to change these associated values every time you use these Member values in code. In swift, When you define an enumeration member, you can associate it with any type, and each member can have different association types if needed. This feature of the enumeration type is similar to the identification union or variant in other languages.
For example, imagine that an inventory tracking system wants to track products through two different bar codes. Some products are identified by a one-dimensional bar code in UPC-A format, using numbers ranging from 0 to 9. Each bar code contains a number that identifies the "Number System", followed by 10 "identifier" numbers, and the last digit used for "check, to ensure that this barcode is correctly scanned and identified:
Other products are identified by QR codes in the QR code format. Such codes can contain any ISO 8859-1 character and can encode a string up to 2953 characters in length:
If you can use a triple with three Integers to store the barcode in UPC-A format, and then use a string that can store any length to store the barcode In QR format, therefore, an inventory tracking system is no longer convenient.
In the swift language, the product barcode enumeration that can define two formats looks like this:
enum Barcode { case UPCA(Int, Int, Int) case QRCode(String)}
You can read this Code as follows:
Defines an enumeration type called barcode, which can have a upca member. This member is associated with a triple containing three integer values, and this enumeration type also has a qrcode member, associated with a string.
This definition does not generate any integer or string value. It just defines that when an immutable variable or variable is equal to barcode. upca orBarcode.QRCodeWhen it is associated with the value type
In this way, a new barcode can be generated using any of the following types:
var productBarcode = Barcode.UPCA(8, 85909_51226, 3)
This example generates a new variable calledproductBarcodeThis variable is associated withBarcode.UPCAType, the value of which is(8, 8590951226, 3)The provided "identifier" value is separated by an underscore-85909_51226 to better be read by a bar code.
The same product can also be assigned another barcode type:
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
At this point, the originalBarcode.UPCAAnd the associated integer value is a new type.Barcode.QRCodeAnd the associated strings are replaced.BarcodeTypes of immutable variables and variable variables can be stored.UPCAOr.QRCodeType (and associated values), but only one of the two types can be stored at a time.
Likewise, the two different types can be checked using the switch statement. At the same time, their associated values can also be obtained in the switch statement. You can regard the associated value as an immutable variable (usingletOr variable (startvarIs Used in the switch control body.
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).")}
If all values associated with an enumerated member are used as immutable variables or variable variables, you can put only oneletOrvarTo achieve the purpose, a brief example:
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 ). ")} // output" QR code with value of abcdefghijklmnop."Original Value
The example of a bar code in the previous section shows how an enumeration type member declares that they can store different types of associated values. Unlike associated values, enumeration members can also pre-set default values (we call them original values). These values are of the same type.
Here is an example of an enumeration member storing an ASCII value:
enum ASCIIControlCharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r"}
An Enumeration type with the original value of the character type is defined here.ASCIIControlCharacterAnd contains some common control characters. For the character type, you can find more descriptions in the character string and character section.
Note that the original value is different from the associated value. The original value should be set to a pre-filled value in the code you define the enumeration, just like the preceding three ASCII codes. The original values of a specific enumerated member are always the same. The Correlated value is set when you create a new constant or variable for enumeration-based members, and can be different each time.
The original value can be a string, character, or any other integer or floating point type. Each original value must be different in its enumeration type definition. If the original value is of the integer type, when other enumeration members do not set the original value, their original value is set to the original value of this integer.
The following enumeration type is for the previousPlantImproved Enumeration type. The new Enumeration type has an original integer value to identify their order from the Sun:
enum Planet: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}
Self-growth meansPlanet.VenusIs set to 2, and so on.
You can obtain the original value of a member by enumerating the toraw () method:
let earthsOrder = Planet.Earth.toRaw()//eathsOrder is 3
Use the fromraw () method of the enumerated member to find the corresponding enumerated member by using an original value. The following example describes how to find the URL of Uranus through the original value 7 of Uranus:
let possiblePlanet = Planet.fromRaw(7)// possiblePlanet is of type Planet? and equals Planet.Uranus”
However, not all integer values can find a correspondingPlanet, Exactly the same way,fromRaw()An unforced enumeration member is returned. In the example shown abovepossiblePlanetIsPlanet?Type, or an unforcedPlanetType.
If you try to find the correspondingPlanet, ThenfromRaw()Unforced responsePlanetType will benil:
Let positiontofind = 9If 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)")} // output "There isn't a planet at position 9"
In this example, we try to use unforced Type Binding to obtainPlanet. Expressionif let somePlanet = Planet.fromRaw(9)Used to retrievePlanetIf you can retrievePlanetThis is not mandatoryPlanetAssignedsomePlanet. In this example, it is impossible to retrieve the correspondingPlanet, SoelseThe included statements will be executed.
Swift QQ Group
Swift mutual communication QQ group: 74512850, so that fans can make progress together! The full Chinese PDF file is available in the group!
Click the link to join the group [swift development mutual assistance]: http://jq.qq.com /? _ WV = 1027 & K = nwgksv
Chinese manual navigation
Blog: Click to enter the navigation bar
GitHub: Click to enter the navigation bar