viktor.radovic viktor.radovic - 1 year ago 91
iOS Question

Change class variables in function has no effect after exiting in Swift

I have one Data class with variable of NSDictionary type

class Data {

var user : String;
var pass : String;
var result: NSDictionary;

init(user: String, pass: String) {
self.user = user;
self.pass = pass;
self.result = NSDictionary();

func networkResponseHandler(data: Foundation.Data?, response:URLResponse?, err:Error? ) -> Void {

if err != nil { print(err); return; }

let jsonResult : NSDictionary = try! JSONSerialization.jsonObject(with: data! as Foundation.Data, options: .allowFragments) as! NSDictionary;


self.result = jsonResult.copy() as! NSDictionary;


func login() -> Bool {
let url = URL(string: "http://");
let task = URLSession.shared.dataTask(with: url!, completionHandler: networkResponseHandler );

return true;

The instance of this class is in AppDelegate file, and im accesing it like this :

let appDelegate = UIApplication.shared.delegate as! AppDelegate

But, in function
when I use breakpoints, I see result has proper values, but outside the function it is empty.

Use of Data object: ViewControler.swift

@IBAction func bSignInPressed(_ sender: AnyObject) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.uData = Data(user: tEmail.text!, pass: tPassword.text!);


Answer Source

The problem is that you are performing an asynchronous request:


In this code you started an asynchronous request, it means that your print code is executed before you receive the data you want to print.

You need to implement your code after you receive the answer, in order to achieve that you need to add a delegate to your task and implement the correct method from NSURLSessionTaskDelegate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download