0
0
iOS Swiftmobile~10 mins

Enums with associated values in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an enum with an associated value.

iOS Swift
enum Vehicle {
  case car([1]: String)
}
Drag options to blanks, or click blank then click option'
Amodel
Bspeed
Ccolor
Dyear
Attempts:
3 left
💡 Hint
Common Mistakes
Using a type name instead of a label for the associated value.
Omitting the label before the colon.
2fill in blank
medium

Complete the code to extract the associated value from the enum using a switch statement.

iOS Swift
let vehicle = Vehicle.car(model: "Sedan")
switch vehicle {
case .car(let [1]):
  print("Model is \(model)")
}
Drag options to blanks, or click blank then click option'
Atype
Bname
Cmodel
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the associated value label.
Forgetting to use let to bind the value.
3fill in blank
hard

Fix the error in the enum declaration by completing the associated value syntax.

iOS Swift
enum Result {
  case success([1] Int)
  case failure(String)
}
Drag options to blanks, or click blank then click option'
Astatus
Bcode
Cerror:
Dvalue:
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the colon after the label.
Using a label without colon or just the type.
4fill in blank
hard

Fill both blanks to declare an enum case with two associated values.

iOS Swift
enum Message {
  case text([1]: String, [2]: Int)
}
Drag options to blanks, or click blank then click option'
Acontent
Blength
Csize
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same label twice.
Omitting the colon after labels.
5fill in blank
hard

Fill all three blanks to create a dictionary from an enum with associated values filtering by a condition.

iOS Swift
let messages = [
  Message.text(content: "Hi", length: 2),
  Message.text(content: "Hello", length: 5),
  Message.text(content: "Hey", length: 3)
]

let filtered = messages.filter { msg in
  if case .text(let [1], let [2]) = msg {
    return [2] [3] 3
  }
  return false
}
Drag options to blanks, or click blank then click option'
Acontent
Blength
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong labels in the pattern matching.
Using the wrong comparison operator.