Enumerations
Learn how to use enumerations to model data in Swift.
StartKey Concepts
Review core concepts you need to learn to master this subject
Defining an Enumeration
Switch Statements
CaseIterable
Raw Values
Associated Values
Instance Methods
Computed Properties
Defining an Enumeration
Defining an Enumeration
enum Day {
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
case sunday
}
let casualWorkday: Day = .friday
Enumerations (or enums) are used to define a new custom type with a list of possible cases. When creating an instance of an enumeration, its value must be one of the cases.
Enumerations
Lesson 1 of 1
- 1With some forms of information, we know all of the possible values that can exist. Let’s say you’re building a transportation app. Users can either travel by truck, plane, or boat. We could just …
- 2Enumerations are a data type found in many popular programming languages, but Swift extends their functionality, offering capabilities one would typically expect to find only in classes. In Swift, …
- 3A switch statement is a common place you might want to use an enum. Switch statements must be exhaustive. This means that each possible case must be addressed explicitly by the control flow. Using …
- 4Enumerations aren’t technically one of the three primary collection types offered by Swift (Arrays, Sets, and Dictionaries). However, they do define a set of cases, and you may find yourself in a s…
- 5In some other programming languages, enumerations are built using another underlying type. For example, in C++, enumerations are actually a set of integers. The Swift implementation of enumeratio…
- 6One of the powerful functionalities Swift adds to enums is the ability to store an associated value of any type attached to a case value. This is different from raw values because each case can hav…
- 7In Swift, enumerations are truly first-class types and have several advanced capabilities. One of those capabilities is the ability to define instance methods inside of an enumeration. One such u…
- 8Another amazing functionality Swift gives with enumerations is the ability to incorporate computed properties. A computed property is a property that isn’t directly stored but is instead derived fr…
- 9Great job 🙌 We have learned about the power and flexibility offered by Swift enumerations. Here’s what we covered: * What an enumeration is * How to use enumerations in a switch control flow * Ho…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory