I just started learning Swift and i'm a little confused. I'm trying to set a variable within an if statement but it's not doing so and it's not returning any errors. I'm not sure if i'm explaining this correctly but here's my code and the output:
var lol:String = "123";
func initiateconnection(){
let url = NSURL(string: "http://www.google.com/")
let session = NSURLSession.sharedSession().dataTaskWithURL(url!){
(data,response, error) in
if error == nil{
var htmldata = NSString(data: data, encoding: NSUTF8StringEncoding)
lol += "0";
}
else{
println("error in connecting");
}
}
session.resume();
println(lol);
}
Output is 123
How come it isn't 1230?
If i do my println within the if statement it works, so my statement does initiate.
(My goal is to store the html in a variable and use it in other functions, but i did the number stuff to make it easier to understand.)
答案 0 :(得分:3)
The URL request you are making is async so it will happen after your println command happens, to see you can add another print statement inside the competition block (where you have lol += '0' and you will see that Xcode will print first 123 and just after 1230 as it will happen just after Xcode get a response from the URL request. I hope that answer your question