Why is self unresolved in Playgrounds?
Code Block import Foundation func startLoad() { let url = URL(string: "https://www.apple.com/")! let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { self.handleClientError(error) return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { self.handleServerError(response) return } if let mimeType = httpResponse.mimeType, mimeType == "text/html", let data = data, let string = String(data: data, encoding: .utf8) { DispatchQueue.main.async { self.webView.loadHTMLString(string, baseURL: url) } } } task.resume() } startLoad()
You're getting a "use of unresolved identifier self" error here because the startLoad() function is a global function in your playground instead of being a method in a class or struct. If you change this to be something like:
then you'll be able to reference self in startLoad(). You'll need to make sure that your class/struct includes any other methods or properties that startLoad() requires.
Code Block import Foundation class MyObject { func startLoad() { /* ... */ } } let object = MyObject() object.startLoad()
then you'll be able to reference self in startLoad(). You'll need to make sure that your class/struct includes any other methods or properties that startLoad() requires.