0
0
Swiftprogramming~5 mins

Enum methods and computed properties in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an enum method in Swift?
An enum method is a function defined inside an enum that can perform actions or return values related to the enum cases. It helps organize behavior specific to the enum.
Click to reveal answer
beginner
What is a computed property in a Swift enum?
A computed property calculates and returns a value each time it is accessed, instead of storing a value. In enums, it can provide extra information based on the current case.
Click to reveal answer
intermediate
How do you define a computed property inside a Swift enum?
You define it like a variable with the keyword var and provide a get block or just return a value directly without storing it.
Click to reveal answer
intermediate
Can enum methods in Swift modify the enum's cases?
No, enum methods cannot change the enum's cases because enums are value types and their cases are fixed. Methods can return new values or perform calculations but not alter the case itself.
Click to reveal answer
beginner
Give an example of a computed property in a Swift enum that returns a description string.
Example:<br>
enum Direction {
  case north, south, east, west
  var description: String {
    switch self {
    case .north: return "Up"
    case .south: return "Down"
    case .east: return "Right"
    case .west: return "Left"
    }
  }
}
Click to reveal answer
What keyword is used to define a computed property in a Swift enum?
Avar
Blet
Cfunc
Denum
Can enum methods in Swift change the enum case itself?
AOnly for raw value enums
BYes, always
COnly if marked mutating
DNo, enum cases are fixed
Which of the following is a valid use of a computed property in an enum?
ACalculating a value based on the current case
BChanging the enum case
CStoring a value permanently
DDefining a new enum case
How do you access a computed property in a Swift enum?
ABy using square brackets
BBy calling it like a function with parentheses
CBy using dot notation without parentheses
DBy importing a special library
What is the purpose of adding methods inside a Swift enum?
ATo store extra data permanently
BTo add behavior related to enum cases
CTo change the enum's raw values
DTo create new enum cases dynamically
Explain how computed properties work inside Swift enums and give an example.
Think about a variable that calculates its value each time you ask for it.
You got /3 concepts.
    Describe the role of methods inside Swift enums and why they are useful.
    Consider how you might add actions related to each enum case.
    You got /3 concepts.