dayonehk.com

The Enchanting World of Enums in Swift Programming

Written on

Understanding Enums

An enumeration, often abbreviated as enum, serves as a datatype that establishes a shared type for a collection of related values, allowing developers to handle these values in a type-safe manner within their code. Unlike traditional C enumerations, which merely assign names to integer values, Swift's enums offer much greater flexibility, enabling the assignment of various raw values, including strings, characters, and all numeric types.

For instance, consider the following syntax to define an enumeration for order statuses:

enum OrderStatus {

case pending

case accepted

case rejected

}

Alternatively, you can define multiple cases on a single line:

enum OrderStatus {

case pending, accepted, rejected

}

In this example, we've introduced a new OrderStatus type, similar to other Swift types like Int or String. This allows for two ways of declaring an instance:

var orderStatus = OrderStatus.rejected

or

var orderStatus: OrderStatus = .rejected

Once initialized, the type of orderStatus is inferred, and you can conveniently change its value using the dot syntax:

orderStatus = .pending

Using Switch Statements with Enums

To evaluate the value of an enumeration variable, a switch statement can be employed:

switch orderStatus {

case .pending:

print("status is pending")

case .rejected:

print("status is rejected")

case .accepted:

print("status is accepted")

}

If you want to manage only some of the values, you can include a default case as well:

switch orderStatus {

case .pending:

print("status is pending")

default:

print("not handled")

}

Iterating Over Enumeration Cases

In certain cases, it might be beneficial to access all cases of an enumeration. To enable this, you can append CaseIterable to the enumeration declaration:

enum OrderStatus: CaseIterable {

}

This allows you to collect all enumeration cases into an array:

var allStatuses = OrderStatus.allCases

Now you can easily iterate through all statuses:

for status in allStatuses {

print(status)

}

Additionally, you can count the number of statuses with:

var allStatusesCount = allStatuses.count // prints 3

Exploring Associated Values

The previous examples illustrate how enumeration cases can hold their own values. However, enums can also have associated values, allowing you to attach additional information to each case. This capability makes Swift enums similar to discriminated unions found in other programming languages.

Here’s an example of an enum that holds associated values:

enum ProductCode {

case qrCode(code: String)

case upc(Int, Int, Int, Int)

}

Now, you can create variables and utilize a switch statement to extract and print the associated values:

var myPhoneCode = ProductCode.qrCode(code: "eqriujlakdsaljdaskjda")

var myLaptopCode = ProductCode.upc(1, 9, 2, 4)

switch myPhoneCode {

case .qrCode(code: let codeUnderHood):

print("Product code type is qrCode with value (codeUnderHood)")

case .upc(let a, let b, let c, let d):

print("Product code type is upc with values = ", a, b, c, d)

}

switch myLaptopCode {

case .qrCode(code: let codeUnderHood):

print("Product code type is qrCode with value (codeUnderHood)")

case .upc(let a, let b, let c, let d):

print("Product code type is upc with values = ", a, b, c, d)

}

This will print:

  • Product code type is qrCode with value eqriujlakdsaljdaskjda
  • Product code type is upc with values = 1 9 2 4

Utilizing Raw Values

At times, you may need to define an enum with raw values that are the same type. For example:

enum Month: Int {

case jan = 1

case feb = 2

case march = 3

case apr = 4

}

In this case, the enum cases are associated with their respective order numbers. Swift allows for implicit raw values, meaning you don’t need to assign a raw value manually for every case. When using integers, Swift automatically assigns values, starting from 0 for the first case:

enum Month: Int {

case jan

case feb

case march

}

print(Month.jan.rawValue) // 0

print(Month.feb.rawValue) // 1

print(Month.march.rawValue) // 2

If you want to assign a specific starting value, you can do so like this:

enum Month: Int {

case jan = 8

case feb

case march

}

print(Month.jan.rawValue) // 8

print(Month.feb.rawValue) // 9

print(Month.march.rawValue) // 10

Initializing from a Raw Value

When you assign a raw-value type to an enum, Swift provides an initializer that can return either an enumeration case or nil based on the raw value provided:

enum Month: Int {

case jan = 1

case feb

case march

}

let secondMonth = Month(rawValue: 2) // optional(feb)

This demonstrates how enums can be initialized based on their raw values.

Summary

In conclusion, Swift enumerations are first-class types that provide extensive capabilities, such as computed properties and initializers. They can also implement protocols to offer standard functionalities. The allCases property allows access to all cases in an enum, while associated values enable flexible data handling. Overall, enums in Swift are a powerful tool for developers.

Thanks

I appreciate your support and interest in my content. It’s a pleasure to share this knowledge with you.

The first video titled "SwiftUI Navigation Made Easy: Harnessing the Magic of Enums" delves into the practical applications of enums in SwiftUI, demonstrating how they simplify navigation and enhance code organization.

The second video titled "The Power of Python Enums" explores how enums function in Python, comparing their capabilities with those in Swift and showcasing their utility in programming.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

# Discover the Transformative Power of Learning an Instrument

Exploring the myriad benefits of learning an instrument, from memory enhancement to stress relief, and why you should start in 2024.

# The Darknet: Unmasking Five Alarming Myths You Should Dismiss

Explore five prevalent myths about the Darknet and uncover the truth behind its digital facade.

AI’s Promising Horizon: Navigating Hype and Reality with Gates and Altman

Gates and Altman discuss the potential of AI as a partner in solving global issues, emphasizing responsible development and human connection.

# Understanding the Logistics of Substance Movement in the Body

Explore how our bodies process, distribute, and eliminate substances, drawing parallels to historical logistical challenges faced during wartime.

The Illusion of Prosperity: Why the 'Winner Takes All' Fails

An exploration of the failures of trickle-down economics and the need for greater equity in society.

Exploring the Concept of Warp Drives: Science and Philosophy

A deep dive into the theoretical implications of warp drives and their philosophical significance.

# The Inevitable Rise of Self-Piloting Aircraft: Challenges Ahead

Exploring the timeline and hurdles of self-piloting planes, covering economic factors and societal implications.

# Discovering the Winter Night Sky: A Guide to Stargazing and the Geminids

Explore the winter sky and learn about the Geminid meteor shower with expert Andrew Fazekas from National Geographic.