Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a function that fetches data from a URL.
iOS Swift
func fetchData(from url: URL, completion: @escaping (Result<Data, Error>) -> Void) [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throws' without marking the function as throwing.
Using 'async' without async context.
Adding '-> Void {' which is redundant here.
✗ Incorrect
The function body starts with an opening brace '{'.
2fill in blank
mediumComplete the code to create a URLSession data task with error handling.
iOS Swift
let task = URLSession.shared.dataTask(with: url) { data, response, error in if let [1] = error { completion(.failure(error)) return } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'data' or 'response' instead of 'error'.
Not unwrapping the optional error properly.
✗ Incorrect
We check if 'error' is not nil to handle errors from the network call.
3fill in blank
hardFix the error in the code to safely unwrap data and call completion with success.
iOS Swift
guard let [1] = data else { completion(.failure(NSError(domain: "", code: -1, userInfo: nil))) return } completion(.success(data))
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Unwrapping 'response' or 'error' instead of 'data'.
Passing the optional 'data' directly without unwrapping.
✗ Incorrect
We unwrap 'data' to ensure it is not nil before using it.
4fill in blank
hardFill both blanks to start the task and resume it.
iOS Swift
let task = URLSession.shared.dataTask(with: url) { data, response, error in // handle response } task[1][2]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'start()' which does not exist.
Forgetting the dot before the method call.
✗ Incorrect
The task is started by calling 'task.resume()'.
5fill in blank
hardFill all three blanks to complete a function that fetches data and handles errors properly.
iOS Swift
func fetchData(from url: URL, completion: @escaping (Result<Data, Error>) -> Void) { let task = URLSession.shared.dataTask(with: url) { data, response, error in if let [1] = error { completion(.failure(error)) return } guard let [2] = data else { completion(.failure(NSError(domain: "", code: -1, userInfo: nil))) return } completion(.success([3])) } task.resume() }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names for unwrapping.
Passing optional 'data' without unwrapping.
✗ Incorrect
We unwrap 'error' to check for errors, unwrap 'data' to ensure data exists, and pass 'data' to success.