Swift Tutorials: Raw Values 🎯

beginner
6 min

Swift Tutorials: Raw Values 🎯

Welcome to our Swift Tutorial on Raw Values! In this lesson, we'll learn about raw values, their purpose, and how to use them in Swift. By the end of this tutorial, you'll be able to work with raw values confidently. Let's get started!

What are Raw Values? 📝

Raw values are associated values that are used to provide a simple representation of the enumeration case. They are an essential part of Swift's enumerations and are often used to create custom data types or flags.

Creating an Enumeration with Raw Values ✅

Let's create an enumeration to represent the days of the week using raw values.

swift
enum Weekdays: Int { case monday, tuesday, wednesday, thursday, friday, saturday, sunday }

In the above example, we've created an enumeration named Weekdays with cases representing each day of the week. The Int type indicates that we'll use integers as raw values for each case.

Accessing Raw Values 💡

You can access the raw value of an enumeration case by using the rawValue property.

swift
let day = Weekdays.tuesday print(day.rawValue) // Output: 1

In the example above, we've created a variable day and assigned it the tuesday case of the Weekdays enumeration. When we print the rawValue property, it outputs the integer 1, which corresponds to the position of tuesday in the enumeration.

Assigning Raw Values Manually 💡

If you want to customize the raw values of your enumeration cases, you can do so by providing an integer value for each case during declaration.

swift
enum DaysOfMonth: Int { case first = 1, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth }

In the example above, we've manually assigned raw values to each case of the DaysOfMonth enumeration.

Raw Value Types 📝

Swift provides several types for raw values, including Int, String, Character, and a custom type. The type you choose depends on your use case and requirements.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of raw values in Swift enumerations?

Stay tuned for our next lesson, where we'll dive deeper into Swift enumerations and explore more practical examples! 🎯