0

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

2
  • 6
    The dataTaskWithURL() method works asynchronously. This has been asked and answered repeatedly. Commented May 24, 2015 at 21:58
  • 1
    Asynchronous code doesn't run synchronously. Commented May 24, 2015 at 23:19

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.