Bird
Raised Fist0
Swiftprogramming~20 mins

Associated values per case in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Associated Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of enum with associated values
What is the output of this Swift code?
Swift
enum Result {
    case success(data: String)
    case failure(errorCode: Int)
}

let response = Result.success(data: "File loaded")
switch response {
case .success(let data):
    print("Success: \(data)")
case .failure(let code):
    print("Error code: \(code)")
}
ACompilation error
BError code: 0
CSuccess: data
DSuccess: File loaded
Attempts:
2 left
💡 Hint
Look at which case is assigned to the variable and what the associated value is.
❓ Predict Output
intermediate
2:00remaining
Extracting multiple associated values
What will this Swift code print?
Swift
enum Shape {
    case rectangle(width: Int, height: Int)
    case circle(radius: Int)
}

let shape = Shape.rectangle(width: 5, height: 10)
switch shape {
case .rectangle(let w, let h):
    print("Area: \(w * h)")
case .circle(let r):
    print("Area: \(3.14 * Double(r * r))")
}
AArea: 50
BArea: 15
CArea: 78.5
DRuntime error
Attempts:
2 left
💡 Hint
Calculate the area of the rectangle using width and height.
🔧 Debug
advanced
2:00remaining
Identify the error with associated values
What error does this Swift code produce?
Swift
enum Device {
    case phone(model: String)
    case tablet
}

let myDevice = Device.phone(model: "iPhone 14")
switch myDevice {
case .phone:
    print("Phone detected")
case .tablet:
    print("Tablet detected")
}
ANo error, prints 'Phone detected'
BError: Missing default case in switch
CError: Associated value 'model' not extracted in case pattern
DRuntime crash due to missing associated value
Attempts:
2 left
💡 Hint
Check if the associated value is handled in the switch case pattern.
🧠 Conceptual
advanced
1:30remaining
Understanding associated values in enums
Which statement about Swift enums with associated values is true?
AAll cases must have the same associated value types.
BEach case can store different types and amounts of associated values.
CAssociated values must be constants and cannot be extracted.
DEnums with associated values cannot be used in switch statements.
Attempts:
2 left
💡 Hint
Think about flexibility of enum cases with associated values.
❓ Predict Output
expert
2:30remaining
Output of nested associated values in enum
What is the output of this Swift code?
Swift
enum Response {
    case success(data: (id: Int, message: String))
    case failure(error: String)
}

let result = Response.success(data: (id: 101, message: "OK"))
switch result {
case .success(let data):
    print("ID: \(data.id), Message: \(data.message)")
case .failure(let error):
    print("Error: \(error)")
}
AID: 101, Message: OK
BError: OK
CID: (101, "OK"), Message: nil
DCompilation error due to tuple usage
Attempts:
2 left
💡 Hint
Look at how the tuple is used as an associated value and accessed.

Practice

(1/5)
1. What is the main purpose of associated values in Swift enums?
easy
A. To store extra data with each enum case
B. To define multiple enums in one declaration
C. To create functions inside enums
D. To inherit properties from other enums

Solution

  1. Step 1: Understand enum cases

    Enum cases represent fixed options, but sometimes need extra data.
  2. Step 2: Role of associated values

    Associated values let each case carry extra information, like a label or number.
  3. Final Answer:

    To store extra data with each enum case -> Option A
  4. Quick Check:

    Associated values = extra data per case [OK]
Hint: Think: extra info stored inside enum cases [OK]
Common Mistakes:
  • Confusing associated values with raw values
  • Thinking enums can inherit properties
  • Believing enums can contain functions only
2. Which of the following is the correct syntax to define an enum case with an associated value of type String?
easy
A. case name -> String
B. case name(String)
C. case name: String
D. case name = String

Solution

  1. Step 1: Recall enum case syntax with associated values

    Associated values use parentheses after the case name with the type inside.
  2. Step 2: Match syntax options

    Only 'case name(String)' uses parentheses correctly for associated values.
  3. Final Answer:

    case name(String) -> Option B
  4. Quick Check:

    Parentheses hold associated value type [OK]
Hint: Use parentheses for associated value types [OK]
Common Mistakes:
  • Using colon instead of parentheses
  • Using equals sign for associated values
  • Using arrow notation incorrectly
3. What will be the output of this Swift code?
enum Result {
    case success(String)
    case failure(Int)
}

let response = Result.success("Done")
switch response {
case .success(let message):
    print(message)
case .failure(let code):
    print("Error code: \(code)")
}
medium
A. Error code: Done
B. Compilation error
C. Error code: 0
D. Done

Solution

  1. Step 1: Identify enum case used

    The variable 'response' is assigned 'Result.success("Done")'.
  2. Step 2: Switch matches .success case

    The switch matches '.success(let message)' and prints the message string.
  3. Final Answer:

    Done -> Option D
  4. Quick Check:

    Matching case prints associated string [OK]
Hint: Match enum case to print its associated value [OK]
Common Mistakes:
  • Confusing success and failure cases
  • Expecting error code instead of message
  • Thinking code will not compile
4. Identify the error in this Swift enum usage:
enum Device {
    case phone(model: String)
    case tablet(model: String)
}

let myDevice = Device.phone("iPhone")
medium
A. Missing parentheses around associated value
B. Enum cases cannot have associated values
C. Cannot assign associated value without label
D. Incorrect enum declaration syntax

Solution

  1. Step 1: Check enum case declaration

    Cases use labeled associated values: 'phone(model: String)'.
  2. Step 2: Check enum instance assignment

    Assigning 'Device.phone("iPhone")' omits the label 'model:'.
  3. Final Answer:

    Cannot assign associated value without label -> Option C
  4. Quick Check:

    Labeled associated values require labels on assignment [OK]
Hint: Use labels when enum cases define labeled associated values [OK]
Common Mistakes:
  • Ignoring labels in associated values
  • Thinking parentheses are missing
  • Believing enums can't have associated values
5. Given this enum with multiple associated values:
enum Message {
    case text(String, Int)
    case image(url: String, size: (width: Int, height: Int))
}

let msg = Message.image(url: "photo.png", size: (width: 100, height: 200))
switch msg {
case .text(let content, let length):
    print("Text: \(content), length: \(length)")
case .image(let url, let size):
    print("Image URL: \(url), size: \(size.width)x\(size.height)")
}
What will be printed?
hard
A. Image URL: photo.png, size: 100x200
B. Text: photo.png, length: 100
C. Image URL: photo.png, size: (100, 200)
D. Compilation error due to tuple

Solution

  1. Step 1: Identify enum case and associated values

    Variable 'msg' is assigned '.image' with url and size tuple.
  2. Step 2: Switch matches .image case and prints values

    Print statement accesses url and tuple's width and height correctly.
  3. Final Answer:

    Image URL: photo.png, size: 100x200 -> Option A
  4. Quick Check:

    Tuple values accessed with dot notation [OK]
Hint: Access tuple parts with dot notation inside switch [OK]
Common Mistakes:
  • Printing tuple as whole instead of parts
  • Confusing .text and .image cases
  • Expecting compilation error from tuple
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard