An import declaration lets you access symbols that are declared outside the current file. The basic form imports the entire module; it consists of the import keyword followed by a module name:
import module
Providing more detail limits which symbols are imported—you can specify a specific submodule or a specific declaration within a module or submodule.
But how can I know which module the URL class belongs to ? We can just search this in Google:
By default, when all top-level code is executed, the execution is terminated. When working with asynchronous code, enable indefinite execution to allow execution to continue after the end of the playground’s top-level code is reached. This, in turn, gives threads and callbacks time to execute.
We set this flag because we have an asynchronous process that would wait for the URL to be accessed and process the response, just as follows:
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guardlet data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
In the above code, we passed a closure function to the dataTask function to process the URL response when the connection succeeded.
let url =URL(string: "http://www.stackoverflow.com")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guardlet data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
Now it works!
4. Summary
In this post, I demonstrated how to solve the ‘cannot find class in scope’ error in xcode playground, be sure to check you have imported the classes you are using .