0
0
Swiftprogramming~5 mins

Enum declaration and cases in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an enum in Swift?
An enum (short for enumeration) is a way to group related values under a common type. It helps organize options or choices in your code.
Click to reveal answer
beginner
How do you declare an enum with cases in Swift?
Use the enum keyword, then list cases inside curly braces. For example:<br>
enum Direction {
  case north
  case south
  case east
  case west
}
Click to reveal answer
intermediate
Can enum cases have associated values in Swift?
Yes! Enum cases can store extra information called associated values. For example:<br>
enum Barcode {
  case upc(Int, Int, Int, Int)
  case qrCode(String)
}
Click to reveal answer
beginner
How do you use an enum case in Swift code?
You create a value by writing the enum name, a dot, then the case name. For example:<br><pre>let direction = Direction.north</pre>
Click to reveal answer
beginner
What is the benefit of using enums instead of strings or numbers for fixed options?
Enums make your code safer and clearer. They prevent mistakes like typos and make it easy to see all possible options in one place.
Click to reveal answer
How do you declare an enum named Color with cases red, green, and blue in Swift?
Aenum Color { case red, green, blue }
Bclass Color { var red, green, blue }
Cstruct Color { let red, green, blue }
Denum Color = [red, green, blue]
Which of these is a valid way to create a value of enum Direction with case east?
Alet d = Direction->east
Blet d = Direction.east
Clet d = Direction[east]
Dlet d = Direction.east()
Can enum cases in Swift have extra data attached?
AOnly if declared as classes
BNo, enums only hold fixed names
CYes, but only strings
DYes, using associated values
What keyword starts an enum declaration in Swift?
Aenum
Bclass
Cstruct
Dcase
Why use enums instead of strings for fixed options?
ABecause enums use less memory
BBecause strings are slower
CTo avoid typos and improve code clarity
DBecause strings cannot be compared
Explain how to declare an enum with multiple cases in Swift and how to create a value from it.
Think about the basic syntax and how you pick a case.
You got /4 concepts.
    Describe what associated values are in Swift enums and give an example.
    Imagine a case that holds more than just a name.
    You got /3 concepts.