Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a URL object from a string.
iOS Swift
guard let url = URL(string: [1]) else { return }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the URL string in quotes.
Passing a variable name that is not defined.
✗ Incorrect
The URL initializer expects a string, so the URL string must be in quotes.
2fill in blank
mediumComplete the code to perform an asynchronous GET request using URLSession.
iOS Swift
let (data, _) = try await URLSession.shared.[1](from: url)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using dataTask which is not async/await compatible.
Using downloadTask which downloads to a file.
✗ Incorrect
The async method to get data from a URL is data(from:).
3fill in blank
hardFix the error in the async function declaration for fetching data.
iOS Swift
func fetchData() async throws -> Data {
let url = URL(string: "https://api.example.com/data")!
let (data, _) = try await URLSession.shared.data(from: url)
return [1]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the URL instead of data.
Returning the response object which is not declared.
✗ Incorrect
The function should return the data received from the network call.
4fill in blank
hardFill both blanks to decode JSON data into a Swift struct.
iOS Swift
let decoder = JSONDecoder() let result = try decoder.[1](MyStruct.self, from: [2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using encode instead of decode.
Passing wrong variable instead of data.
✗ Incorrect
Use decode method to decode JSON data. The data variable holds the JSON bytes.
5fill in blank
hardFill all three blanks to complete the async function that fetches and decodes JSON.
iOS Swift
func fetchAndDecode() async throws -> MyStruct {
guard let url = URL(string: [1]) else { throw URLError(.badURL) }
let ([2], _) = try await URLSession.shared.data(from: url)
let decoder = JSONDecoder()
return try decoder.decode([3].self, from: data)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting the URL string.
Using wrong variable names for data.
Passing wrong type to decode.
✗ Incorrect
The URL string must be quoted, data holds the downloaded bytes, and MyStruct is the type to decode.