ThisClark ThisClark - 5 months ago 212
Swift Question

Reference to property in closure requires explicit 'self.' to make capture semantics explicit

Trying to load HTML from a web service into a webview, I get this error:

Reference to property 'webviewHTML' in closure requires explicit 'self.' to make capture semantics explicit


What does it mean, and how can I load the HTML string into my web view?

func post(url: String, params: String) {

let url = NSURL(string: url)
let params = String(params);
let request = NSMutableURLRequest(URL: url!);
request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
print("error=\(error)")
return
}

var responseString : NSString!;
responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
webviewHTML.loadHTMLString(String(responseString), baseURL: nil)
}
task.resume();
}

Answer

Very simple - the answer is literally in the error message - self refers to the class, and if webviewHTML is a property of the class and it is declared outside of the closure, then self is required to use the webviewHTML property inside the closure.

Change this line:

self.webviewHTML.loadHTMLString(String(responseString), baseURL: nil)