-3

how do I modify a value within a closure or at least get data from a closure in Swift? I have a global variable declared outside a class and I am trying to modify it from within a closure or completion block; however, it is not modified and I cannot get data from inside a closure.

  var someGlobalVariable = 0 

  class someClass{


dispatch_async(dispatch_get_main_queue(), { () -> Void in

                        someGlobalVarible += 1 






                    })
  }

   print(someGlobalVariable) // returns 0 and not 1 
}
  • It's better if you post an example that is not working for you, because you can modify external variables without doing anything special. You could have retain cycles, but that's another question. – uraimo Jul 10 '16 at 19:42
  • 1
    That example doesn't compile. – zneak Jul 10 '16 at 19:54
  • 1
    That's not valid swift code. I don't recommend to try code you don't understand (and that's horribly broken), read the Swift book by Apple before doing anything else. – uraimo Jul 10 '16 at 19:54

2 Answers2

1

If I remember correctly you can access the global variable by adding self. to the variable inside the closure

self.someGlobalVariable
brushedred
  • 41
  • 3
0

You have to print the variable after it gets updated.

dispatch_async(dispatch_get_main_queue(), { () -> Void in

    someGlobalVarible += 1 
    print(someGlobalVariable) // will print 1
})
}
Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61