Swift Tutorials for Front-end Developers: Enumerations
Master Swift in 2024 and Start Developing Your Own iOS/macOS App

Welcome to the Mastering Swift tutorial series, in this article we will introduce defining enums, iterating through enums, enum raw values, and associated values in Swift.
Next, we launch Xcode and select “File” > “New” > “Playground”. Create a new Playground and name it “Enumerations”.
- Optional parameters, Variadic parameters, In-out parameters, and Function types
- Closure expressions, Trailing closures, and Escape closuress
- Defining enums, Enum raw values, and Enum associated values
- Classes and Class inheritance, Optional properties, Type properties, and Property observers
- Protocol Conformance, Protocol Composition, Protocol Inheritance
- Structure Stored Properties, Computed Properties, Type Properties, Property Observers
In Swift, an enumeration is a special data type that allows you to define a set of related values. These values are specific options you will use in your program.
Defining an Enumeration
In Swift, we use the enum keyword to define an enumeration, and the case keyword inside the enumeration body to define different situations. Each situation represents a member of the enumeration.
Swift Code
enum Color {
case red
case green
case blue
}
let greenColor = Color.green
print(greenColor)
// Output: greenIn the above code, we define an enumeration called Color, which contains three colors.
TypeScript Code
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Green;
console.log(color);
// Output: 1Handling Enumerations With Switch
With the Color enumeration, we can use the switch statement to process the enumeration.
Swift Code
enum Color {
case red
case green
case blue
}
func describeColor(color: Color) {
switch color {
case .red:
print("Color is red.")
case .green:
print("Color is green.")
case .blue:
print("Color is blue.")
}
}
describeColor(color: .blue)
// Output: Color is blue.TypeScript Code
enum Color {
Red,
Green,
Blue
}
function describeColor(color: Color): void {
switch (color) {
case Color.Red:
console.log("Color is red.");
break;
case Color.Green:
console.log("Color is green.");
break;
case Color.Blue:
console.log("Color is blue.");
break;
}
}
describeColor(Color.Blue);
// Output: "Color is blue." Iterate Over the Members of an Enumeration
In Swift, we can use the CaseIterableprotocol to make the enumeration follow the iterable protocol to traverse the enumeration members.
Swift Code
enum Color: CaseIterable {
case red, green, blue
}
for color in Color.allCases {
print(color)
}
/**
Output:
red
green
blue
*/In the above code, we make the Color enumeration follow the CaseIterable protocol so that all members of the enumeration are enumerated.
TypeScript Code
enum Color {
Red,
Green,
Blue
}
for(let colorKey in Color) {
console.log(colorKey)
}
/**
Output:
"0"
"1"
"2"
"Red"
"Green"
"Blue"
*/Enumerations With Raw Values
In Swift, enums can be associated with raw values, which can be of types such as integers, floating-point numbers, strings, and more. The raw values for enums provide a default value for each member, making it convenient to use them in different contexts.
Creating an Enum With Ints
Swift Code
enum Weekday: Int {
case sunday = 1
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}
let today: Weekday = .tuesday
let rawValue: Int = today.rawValue
print(rawValue)
// Output: 3In the above code, we define an enumeration Weekday that represents the day of the week and explicitly assigns a primitive value to each member. By default, the first member has a primitive value of 1, and subsequent members have primitive values that are incremented.
TypeScript Code
enum Weekday {
Sunday = 1,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
let today: Weekday = Weekday.Tuesday;
let rawValue: number = today;
console.log(rawValue);
// Output: 3In TypeScript, the raw values of numeric enums are also incremented, similar to numeric enums in Swift.
Creating an Enum With Strings
Swift Code
enum Direction: String {
case up = "UP"
case down = "DOWN"
case left = "LEFT"
case right = "RIGHT"
}
let move: Direction = .up
let directionString: String = move.rawValue
print(directionString)
// Output: UPIn the above code, we define a string enumeration Direction, explicitly assigning a string primitive value to each member.
TypeScript Code
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let move: Direction = Direction.Up;
let directionString: string = move;
console.log(directionString);
// Output: "UP"String enum primitives are similar in TypeScript, allowing you to specify string type primitives for each member.
Enumerations With Associated Values
In Swift, enums can not only have raw values but also carry associated values. Associated values allow specifying the data type each member of the enum carries when defining it. This way, each enum member can carry data of different types.
Swift Code
import Foundation
// Define an enumeration to represent different graphic shapes
enum Shape {
case circle(radius: Double)
case square(side: Double)
case rectangle(width: Double, height: Double)
}
// Create different graphs using associated values
let circle: Shape = .circle(radius: 3.0)
let square: Shape = .square(side: 4.0)
let rectangle: Shape = .rectangle(width: 3.0, height: 4.0)In the above code, we define a Shape enumeration, each member of which can carry different types of associated values, representing different graphic shapes.
With the Shape enumeration, we can create a calculateArea function to calculate the areas of different shapes.
Swift Code
// Calculate the area of a shape using associated values
func calculateArea(shape: Shape) -> Double {
switch shape {
case .circle(let radius):
return Double.pi * pow(radius, 2)
case .square(let side):
return pow(side, 2)
case .rectangle(let width, let height):
return width * height
}
}
// Calculate the area of different shapes
let areaOfCircle = calculateArea(shape: circle) // 28.27433388230814
let areaOfSquare = calculateArea(shape: square) // 16
let areaOfRectangle = calculateArea(shape: rectangle) // 12In the above code, we define a function calculateArea to calculate the area of a graphic based on its type. By associating values, we can easily extract the properties of different graphs for calculations.
In TypeScript, since there is no direct syntax for Swift enum associated values, we can use TypeScript’s union types to simulate this behavior.
TypeScript Code
// Define different graphics
interface Circle {
kind: 'circle';
radius: number;
}
interface Square {
kind: 'square';
side: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
// Using union types to represent graphic shapes
type Shape = Circle | Square | Rectangle;In the above code, we use interfaces and union types to define the data structures of different graphs. Afterward, we can also define a calculateArea function to calculate the areas of different shapes.
TypeScript Code
function calculateArea(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * Math.pow(shape.radius, 2);
case 'square':
return Math.pow(shape.side, 2);
case 'rectangle':
return shape.width * shape.height;
default:
throw new Error('Invalid shape');
}
}
const circle: Circle = { kind: "circle", radius: 3.0 }
const square: Square = { kind: "square", side: 4.0 }
const rectangle: Rectangle = { kind: "rectangle", width: 3.0, height: 4.0 }
// Calculate the area of different shapes
const areaOfCircle = calculateArea(circle); // 28.274333882308138
const areaOfSquare = calculateArea(square); // 16
const areaOfRectangle = calculateArea(rectangle); // 12Enumerations With Computed Properties
Swift Code
enum Color {
case red, green, blue
var hexValue: String {
switch self {
case .red:
return "#FF0000"
case .green:
return "#00FF00"
case .blue:
return "#0000FF"
}
}
}
let greenColor = Color.green
print(greenColor.hexValue)
// Output: #00FF00In the above code, we added a computed property hexValue to the Colorenumeration, which is used to represent the hexadecimal value of the color.
Enumerations With Methods
Swift Code
enum Color {
case red, green, blue
func description() -> String {
switch self {
case .red:
return "Color is red."
case .green:
return "Color is green."
case .blue:
return "Color is blue."
}
}
}
let greenColor = Color.green
print(greenColor.description())
// Output: Color is green.In the above code, we added a method description to the Color enumeration to return the description information of the color.
In this article, we introduce how to define enumerations, traverse enumerations, enumerate raw values, enumerate associated values, etc. in Swift. By comparing it with TypeScript syntax, I hope it can help you better understand the related features of Swift. If you want to learn Swift, follow me on Medium or Twitter to read more about Swift and TS!
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.






