SoFunction
Updated on 2025-04-11

Detailed explanation of enumeration types of Swift programming

I believe that children's shoes who have written programs are not unfamiliar with enum types. There are many benefits of using enum types, so I won't go into too much detail here. There are countless enumerations in the Fundation framework and UIKit. Enumerations can make your code easier to read and improve maintainability. The enumeration in the Swift language is eye-catching. Enumeration in Swift not only retains the features of enumeration in most programming languages, but also adds some useful and practical new features. In this article, we will appreciate the charm of enumeration types in Swift.

Some friends will ask, isn’t it just an enumeration? What’s there to say? Why is it not the case with enums in Swift? The functions of enums in Swift are much more powerful. They can not only bind values ​​to enum elements, but also associate multiple values ​​to enum elements. At the same time, they can also assign an enum value to an enum variable through the value of the element, and an enum function can be defined in the enum. Below we will start to peek at the enums in Swift.

1. Define enumeration

The definition of enumeration in Swift is different from that of other programming languages. Each enumeration element has an additional keyword case, followed by the enumeration element. The following are two ways to define the enumeration type.

1. Multiple cases, each enumerated element has a case in front of it

//Definition of enumerationenum KindOfAnimal {
 case Cat
 case Dog
 case Cow
 case Duck
 case Sheep
} 

2. One case solves all elements, and use commas to separate the enum elements.

 //You can also define the enum typeenum KindOfAnimalTwo {
 case Cat, Dog, Cow, Duck, Sheep
 }

2. Use of enumeration types

The enum type is defined for the purpose of using it, right? Just use the enum type to declare variables. In Swift, there is no need for typedef to define the enum type. We can directly use the enum type.

//Define enumeration variables and assign valuesvar animal1: KindOfAnimal = 

When assigning values ​​to enumeration variables, the enumeration type name can also be omitted, because the type of the enumeration variable has been specified when declaring the enumeration variable.

var animal2: KindOfAnimal = .Dog 

Use our enum variables in Switch

//Use enums in Switch…Caseswitch animal1 {
 case :
 println("Cat")
 case :
 println("Dog")
 case :
 println("Cow")
 case :
 println("Duck")
 case :
 println("Sheep")
 default:
 println("error = hehe")
}

3. Assign values ​​to enum members

When declaring an enum in Swift, you can assign a value to each enum member. The following member of the City enum is specified with a value, as shown below:

// Assign values ​​to the enumenum City: String{
 case Beijing = "Beijing"
 case ShangHai = "Shanghai"
 case GuangZhou = "Guangzhou"
 case ShengZhen = "Shenzhen"
}

Use the rawValue of the enumeration variable to get the value assigned to each enumeration member, the code is as follows:

//Define enumeration variables and assign valuesvar myInCity: City = 

//Get the value of the enumeration variablevar myInCityString: String = ;
println(myInCityString) //Output: Beijing

4. Assign values ​​to enumeration variables through the values ​​of enumeration members

What is to assign values ​​to enum variables through the values ​​of enum members? For example, the above enum type City is an example. If we only know that the value of an enum member is "Beijing", but not that the enum member corresponding to the value of "Beijing" is "Beijing", in Swift, you can assign an enum member "Beijing" to the enum variable through the value of "Beijing".

Is it a bit confusing? Let's take a look at the example. The following is the code to assign values ​​to the enum variables through the original values ​​of the enum member.

// Assign values ​​to enumerate members by enumerating the values ​​of membersvar youInCity: City? = City(rawValue: "Beijing");
 

Why is our youInCity of optional value type? The reason is very simple. We are not sure whether the value of the member in the enumeration City contains "Beijing". The value of the enumeration variable youInCity is uncertain, so it is an optional type. Let's take out the value of youInCity and first determine whether youInCity is. If so, it means that the value is successfully assigned and the value is output.

//Take out the value in youInCityif youInCity ==  {
 var cityName: NSString = youInCity!.rawValue
 println(cityName) //Output: Beijing}

Find a string that does not contain the value of an enumeration member to assign values ​​to the enumeration variables. Observe the result. The following testCity value is printed as nil, because no member in the enumeration has the value of "Beijing".

//Pass in an enum that does not have a valuevar testCity: City? = City(rawValue: "Beijing");

// testCity is nilprintln(testCity)

5. The enum value increases automatically

Good things still need to be preserved. If the enum value in Swift is an integer, the following will increase after the first assignment. I won’t say much about the autoincrement of enumeration value, just look at the examples.

//The enum value increases by itselfenum Hour: Int{
 case One = 1
 case Two
 case Three
 case Four
 case Five
 case Six
 case Seven
 case Eight
}

var hourTest: Int = 
println(hourTest) // hourTest = 8

6. Enumerate the associated values

What are the associated values ​​of enums? Literally speaking, it is to associate a value to the enum member. Yes, it means to associate a value to the enum variable when assigning a value to the enum variable. How to do it in Swift? It is to use brackets to define the type of the associated value when declaring elements in the enumeration type, and then associate one or more values ​​when assigning values ​​to the enumeration variables, and look at the example directly.

The following code specifies two associated values ​​of String type to iOS, and associates two values ​​when assigning values ​​to enumeration variables. Associating these two values ​​can be used in a Switch statement.

//The associated value of the enumerationenum mobileLanguage{
 case IOS (String, String)
 case Android (String)
}

var iPhone: mobileLanguage = ("Objective-C", "Swift")

switch iPhone {
 case (let language1, let language2):
 println("language1 = \(language1), language2 = \(language2)")
 
 case (let temp):
 println(temp);
 default:
 println("NO")
}

//Output result: language1 = Objective-C, language2 = Swift

7. Enumeration functions

Enumerations in Swift can add functions, is there any illumination? The following code snippet adds a descriptive function based on the above associated value code, which returns the enumeration information of the current enumeration variable, as shown in the following code snippet:

//Enum functionenum mobileLanguageFun{
 case IOS (String, String)
 case Android (String)
 //Define the enumeration function var description: String{
 switch self {
 case (let language1, let language2):
 return "language1 = \(language1), language2 = \(language2)"
 
 case (let temp):
 return temp
 default:
 return ("NO")
 }

 }
}

var myMobile: mobileLanguageFun = ("objc", "swift")

println() //language1 = objc, language2 = swift

The above is all about this article, I hope it will be helpful for everyone to learn swift software programming.