Level: ★☆☆ tag: “iOS” “Swift 5.1” “enumeration” “Iterative enumeration” “Enumeration associated Values” “Recursive enumeration” author: Muling Low review: QiShare team
Enumeration: Indicates the Enumeration type
An enumerated type is a common type defined for a set of associated values that can be handled in code in a type-safe manner. Enumeration types in C represent the associated enumeration items as integer values. Enumerations in Swift are more flexible and do not provide values for enumerations. If you provide a value for an enumeration item (then the value is called a raw value), the value can be a string, a character, any integer, or a floating-point value. In addition, enumerations can specify any type of associated value to be stored with the enumeration item’s value. We can define a generic set of related items as part of an enumeration, with each enumeration associated with a different set of values of a more appropriate type. At the same time, enumerations in Swift adopt many features that only classes support, such as enumerations:
- The ability to provide computational properties that support enumerating additional information beyond the current value;
- The ability to provide instance methods to support functionality related to the values represented by enumerations;
- The ability to define initialization methods that provide the value of the initial enumeration item;
- Can support extension, can extend its function on the basis of the original implementation;
- Ability to comply with protocols and provide all standard functions;
The enumeration of grammar
Use the enum keyword to introduce enumerations and put their entire definition in {}
enum <#name#> {
case <#case#>
}
Copy the code
Definition and use of enumerations
enum CompassPoint {
case north
case west
case east
caseSouth} // Multiple enumerations on a single line. enum CompassPoint {case north,west,east,south
}
Copy the code
Each enumeration definition defines a new type.
var direction : CompassPoint = .north
var direction = CompassPoint.north
Copy the code
Use Switch statements to match enumerated values
let direction : CompassPoint = .north
switch direction {
case .east:
print("ease")
case .north:
print("north")
case .west:
print("west")
case .south:
print("south")}Copy the code
Iterative enumeration
You can make an enumeration have a collection of all enumerations by using: CaseIterable after the enumeration name. The collection is retrieved by calling the allCases property of the enumeration type.
enum CompassPoint : CaseIterable{
caseNorth, West, East, Southlog:[swift_basic.EnumerationPractice.CompassPoint.north, swift_basic.EnumerationPractice.CompassPoint.west, swift_basic.EnumerationPractice.CompassPoint.east, swift_basic.EnumerationPractice.CompassPoint.south]
*/
print(CompassPoint.allCases)
switch CompassPoint.allCases.first! {
case .north:
print("Output correct")
default:
print("Output failed"} //eachCase each item is an example of an enumerated typefor eachCase in CompassPoint.allCases {
/*north
west
east
south*/
print(eachCase)
}
Copy the code
Enumeration associated value
Enumeration types store additional values of other types next to enumeration items, which are called associated values. And every time you use an enumeration item with an associated value in your code, the associated value will be different. Enumerations can be defined in Swift to store associated values of any given type, and each enumeration item can have a different value type. For example, the product code has two forms: two-dimensional code and bar code. The information of the two-dimensional code can be extracted as String type, and the information of the bar code is a String of numbers, which can be associated with the tuple type of (Int,Int,Int) according to the format of: one digit system number + five digit manufacturer id + five digit product ID + one digit check number. So we use the associated value to define the enumeration type as follows: general commodity bar code
enum ProductCode {
caseUpc (Int,Int,Int,Int)// General commodity barcodecaseQrCode (String)}Copy the code
An enumeration type ProductCode is defined with two enumerations upC and qrCode. These two enumerations can store (Int, Int, Int, Int) and String associated values, respectively. The ProductCode enumeration type definition does not provide any meaningful Int or String values. It only defines the type of associated values that ProductCode constants and variables can store if they are equal to productcode.upc or productcode.qrcode.
var productCode = ProductCode.upc(1, 22, 333, 4444)
productCode = ProductCode.qrCode("Qr code ha")
Copy the code
Use the Switch statement to match enumerations and extract their associated values. You can use let and var to extract each associated value as a constant or variable for use in the body of the case.
var productCode = ProductCode.upc(1, 22, 333, 4444)
switch productCode {
case .upc(let x, let y, let z, let zz):
print("Extracted from a switch statement that matches the enumeration of associated values for x: \ (x), y: \ (y) z: \ (z) zz: \ (zz)")
case ProductCode.qrCode(let str):
print("The associated value of the matching enumeration extracted from the switch statement is :\(STR)")
}
productCode = ProductCode.qrCode("Qr code ha")
switch productCode {
case let .upc(x, y, z, zz):
print("Extracted from a switch statement that matches the enumeration of associated values for x: \ (x), y: \ (y) z: \ (z) zz: \ (zz)")
case let .qrCode(str):
print("The associated value of the matching enumeration extracted from the switch statement is :\(STR)")}Copy the code
Enumerate raw values
The example of associated values shows how enumerations declare that they store different types of associated values. Instead of associated values, enumerations can also prepopulate default values (called raw values), which are of the same type.
enum NameType : String{
case ZhangFei = "Zhang fei"
case GuanYu = "Guan yu"
case LiuBei = "Liu bei"
}
let name = NameType.ZhangFei
print(name.rawValue)//! <log: zhang feiCopy the code
The raw value of the enumerated NameType is defined as String and set to the raw value. The original value can be a string, a character, or any integer or floating-point type. Each primitive value must be unique in its enumeration declaration. The original value is different from the associated value. Raw value: A pre-populated default value that is always the same for a particular enumeration item. Associated value: Each time a constant or variable is created based on one of the enumeration cases, its associated value can be different.
Assign raw values implicitly
When you use enumerations with raw values of integer or string type, you don’t have to explicitly assign raw values to each case. Because Swift will automatically assign us a value. For example, when integers are used for raw values, each case has one more implied value than the previous case. If no value is set in the first case, the value is 0. You can access the rawValue of an enumeration item using the rawValue property.
enum Planet: Int,CaseIterable {
caseMercury = 1, Venus, earth, Mars, Jupiter, Saturn, Uranus, Neptune"Raw values of enumeration type Planet entries"
for item in Planet.allCases {
planetOutStr += "\(item) : \(item.rawValue) "
}
print(planetOutStr)//! < enumeration type Planet primitive values mercury: 1 Venus: 2 Earth: 3 Mars: 4 Jupiter: 5 Saturn: 6 Uranus: 7 Neptune: 8Copy the code
An enumeration whose raw value is a string. The original value implicitly assigned to each enumeration is the name of the enumeration.
enum CompassPoint :String,CaseIterable{
case north,west,east,south
}
var directionOutStr = "Enumerate the original value of the CompassPoint entry."
for item in CompassPoint.allCases {
directionOutStr += "\(item) : '\(item.rawValue)' "
}
print(directionOutStr)//! < the original value of the entry of the enumerated type CompassPoint north:'north' west : 'west' east : 'east' south : 'south'
Copy the code
Class from the original value
If you define an enumeration using a rawValue type, the enumeration automatically receives a parameter name: rawValue parameter type: the original method of the rawValue type, and returns an enumeration item or nil. We can use this initialization method to try to create a new instance of the enumerated type.
letpossiblePalnet = Planet.init(rawValue: 7) //! < Planet type optional. Optional (swift_basic EnumerationPractice. Planet. Uranus) / / enumeration cannot match according to the original value of the situationletpossiblePalnet = Planet.init(rawValue: 9)//! < Planet type optional. 9 is beyond the scope of all items in the enumeration.log:nil // Unpack, optional bindingif let possiblePlanet = possiblePalnet {
print(possiblePlanet)
switch possiblePlanet {
case .earth:
print("The earth")
default:
print("Other planets")}}else {
print("No suitable enumeration found")}Copy the code
Recursion of enumerations
When you define an enumeration, the system automatically prompts you to add the indirect keyword when a case of the enumeration type associates one or more values of the enumeration type because the enumeration type is already defined as a recursive enumeration with a recursive structure. Indicate that the enumeration item is recursive by using the indirect keyword before it. The following example stores a definition of a recursive enumeration of three mathematical expressions.
// Method one // Recursive enumeration, which stores three mathematical expressions using 'indirect' to denote enumeration items that can be recursively called. enum ArithmeticExpression {case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
Copy the code
Use the indirect keyword before the enumeration begins to enable recursion for all enumeration items with associated values:
Indirect enum ArithmeticExpression {case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
Copy the code
Each item of the ArithmeticExpression enumeration type has a corresponding correlation value set, And both addition and using x are associated with a value that can store the (ArithmeticExpression, ArithmeticExpression) type. That is, two ArithmeticExpression enumerated types are associated respectively.
Nesting of recursive enumerations:
// Stores an associated value of 5letFive = ArithmeticExpression number (5) / / store the associated values for 6letSix = ArithmeticExpression. Number (6) / / store a 3 associated valuesletThree = ArithmeticExpression number (3) / / addition enumeration, link the two current value of an enum type.letSum = ArithmeticExpression. Addition (five, six) / / multiplication enumeration, link the two current value of an enum type.letMultiplication = ArithmeticExpression. Multiplication (sum, three) / / mathematical expression of the present form.Copy the code
Create a recursive function using a multi to verify that it can calculate the correct result
// Create a recursive function to validate recursion func arithmeticOperation(_ expression: ArithmeticExpression) -> Int {switch expression {case let .number(x):
return x
case let.addition(x, y): //! Here x and y are still expressions, so we need to recurse first to get the associated value of type 'Int'return arithmeticOperation(x) + arithmeticOperation(y)
case .multiplication(let x, lety): //! Here x and y are still 'ArithmeticExpression', so we need to recursively calculate the correlation value of type 'Int' firstreturn arithmeticOperation(x) * arithmeticOperation(y)
}
}
print(The result of a recursive call to a nested mathematical expression is: \(arithmeticOperation(multi)).) / /! <logThe result of recursive calls to nested mathematical expressions is: 33Copy the code
Resources: Swift 5.1 official programming guide
To learn more about iOS and related new technologies, please follow our official account:
You can add the following xiaobian wechat, and note to join the QiShare technical exchange group, xiaobian will invite you to join the QiShare technical Exchange Group.
QiShare(Simple book) QiShare(digging gold) QiShare(Zhihu) QiShare(GitHub) QiShare(CocoaChina) QiShare(StackOverflow) QiShare(wechat public account)
Recommended articles: IOS add click events to UILabel with SwiftUI Add animation to view with SwiftUI Write a simple page Swift 5.1 (7) – closure iOS App startup optimization (three) — make a tool to monitor the App startup time iOS App startup optimization (2) — use “Time Profiler” tool to monitor App startup Time iOS App startup optimization (1) — understand the App startup process qidance Weekly