0
0
Swiftprogramming~10 mins

Associated values per case in 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 define an enum case with an associated value.

Swift
enum Result {
    case success([1]: String)
}
Drag options to blanks, or click blank then click option'
Amessage
Bvalue
Cinfo
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using a type name instead of a variable name for the associated value.
Omitting the associated value name.
2fill in blank
medium

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

Swift
let result = Result.success(message: "Done")
switch result {
case .success(let [1]):
    print([1])
default:
    break
}
Drag options to blanks, or click blank then click option'
Ainfo
Bvalue
Cdata
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the associated value name.
Forgetting to use the variable in the print statement.
3fill in blank
hard

Fix the error in the enum definition with multiple associated values.

Swift
enum NetworkResponse {
    case error(code: Int, [1]: String)
}
Drag options to blanks, or click blank then click option'
Aerror
Bmessage
Cstatus
Ddescription
Attempts:
3 left
💡 Hint
Common Mistakes
Using a type name instead of a variable name.
Using a name that conflicts with the first associated value.
4fill in blank
hard

Fill both blanks to create a function that returns the associated value from the enum.

Swift
func getMessage(from response: NetworkResponse) -> String? {
    switch response {
    case .error(_, let [1]):
        return [2]
    default:
        return nil
    }
}
Drag options to blanks, or click blank then click option'
Amessage
Berror
Ddescription
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for extraction and return.
Trying to return the ignored code value.
5fill in blank
hard

Fill all three blanks to define an enum with multiple cases and associated values, and create an instance.

Swift
enum Device {
    case phone([1]: String)
    case tablet([2]: Int)
    case laptop([3]: String)
}

let myDevice = Device.phone(model: "iPhone 14")
Drag options to blanks, or click blank then click option'
Amodel
Bsize
Dtype
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent or duplicate names for associated values.
Not matching the associated value name when creating the instance.