String nil inside NSURLSession

前端 未结 1 1897
囚心锁ツ
囚心锁ツ 2021-01-27 10:56

I declare a string in the beginning

var testString: String?


let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in

    let         


        
相关标签:
1条回答
  • 2021-01-27 11:51

    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.

    0 讨论(0)
提交回复
热议问题