Ad space (banner)
๐ŸฆSwift Lessons
Lesson 41 / 68

Enum (Enumerated Types) Basics

In this lesson you will learn the basics of enums in Swift, so a fixed set of options can be referred to by readable names. This is for anyone searching for "Swift enum how to use".

Swift's enum creates an enumerated type representing a fixed set of options, and is a core feature of the language. Use it when you want to limit the possible values in advance, the way a traffic light only has red, green, and amber.

The sample code gives the Color enum three cases - red, green, blue - and assigns one to a variable as Color.red. Notice how rawValue reads the underlying string value.

A common stumbling block for beginners is just how much an enum can do. It can carry associated values and methods, which makes it one of Swift's most powerful and expressive features, and correspondingly hard to take in all at once.

In real-world development, a named enum conveys intent far better than a string or a number scattered through the code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)