I declare a string in the beginning
var testString: String?
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let
The reason your variable is nil is because closures are executed asynchronously. That means that the rest of the code after the network request will continue to be called as normal, but the code containing parameters data, response and error is only called when the network request is finished.
To work around this, try putting whatever you are trying to do with the variable inside the closure, so your println(testString)
would be inside the curly brackets.