Swift Enum Methods 🎯

beginner
19 min

Swift Enum Methods 🎯

Welcome back, programmer! Today, we're diving into the fascinating world of Swift Enum methods. These powerful tools will help you create more organized, maintainable, and flexible code. Let's get started! 📝

What are Enum Methods? 💡

In Swift, Enum (Enumeration) is a data type that represents a set of related values. We can add methods to our enums to make them even more useful.

swift
enum Shape { case circle(radius: Double) case rectangle(width: Double, height: Double) func area() -> Double { switch self { case let .circle(radius): return 3.14 * radius * radius case let .rectangle(width, height): return width * height } } }

In this example, we created an enum Shape with two cases: circle and rectangle. We also added a method area() to calculate the area of each shape.

Creating Instance Methods 💡

Instance methods are methods defined on specific instances of an enum. You can use them to access and manipulate the values stored in the enum cases.

swift
enum Shape { case circle(radius: Double) case rectangle(width: Double, height: Double) func area() -> Double { switch self { case let .circle(radius): return 3.14 * radius * radius case let .rectangle(width, height): return width * height } } func circumference() -> Double { switch self { case let .circle(radius): return 2 * 3.14 * radius case let .rectangle(_, _): // Error: Cannot call 'circumference()' on a rectangle fatalError("Cannot calculate circumference for a rectangle") } } } let circle = Shape.circle(radius: 5.0) let area = circle.area() // 78.53981633974483 let circumference = circle.circumference() // 31.41592653589793

In this example, we added a method circumference() to calculate the circumference of a circle. We also defined how to handle the rectangle case when we try to call circumference().

Creating Static Methods 💡

Static methods are methods defined on the enum itself, not on specific instances. They can be useful when you want to provide shared functionality across all instances of the enum.

swift
enum Shape { case circle(radius: Double) case rectangle(width: Double, height: Double) static func averageArea(shapes: [Shape]) -> Double { var totalArea: Double = 0 for shape in shapes { totalArea += shape.area() } return totalArea / Double(shapes.count) } } let shapes: [Shape] = [ .circle(radius: 2.0), .rectangle(width: 3.0, height: 4.0), .circle(radius: 1.0) ] let averageArea = Shape.averageArea(shapes: shapes) // 2.666666666666667

In this example, we added a static method averageArea(shapes:) to calculate the average area of an array of shapes.

Practice Time 💡

Now that you've learned about enum methods, let's test your knowledge!

Quick Quiz
Question 1 of 1

What is the output of the following code?

Stay tuned for our next lesson, where we'll explore more advanced topics related to Swift Enum methods! 🚀