Use of unresolved identifier ’self’ in Playgrounds for iPad

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()


Answered by Developer Tools Engineer in 614093022
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:

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.
This startLoad function isn't defined in the context of a class or struct, which is what self would refer to.

You could create a class called MyLoader or something, define the function on the type and then create an instance of the type and call the startLoad function on it...

Based on that code above you'll also need a webView property on your MyLoader class, as well as a handleServerError and handleServerError method defined.
Accepted Answer
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:

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.
Use of unresolved identifier ’self’ in Playgrounds for iPad
 
 
Q