[swift-users] Capture values by Closures in different background threads.

Jeremy Pereira jeremy.j.pereira at googlemail.com
Wed Nov 30 11:07:03 CST 2016


> On 30 Nov 2016, at 10:38, Седых Александр via swift-users <swift-users at swift.org> wrote:
> 
> Assume we have this code:
>  
> Immediately two Timer's closures captured two copy of initial values of instance Test, with internal num values is 0.
>  
> //: Playground - noun: a place where people can play
>  
> import UIKit
>  
> var str = "Hello, playground"
>  
> struct Test {
>     var num = 0
>     mutatingfunc newNum(new: Int) {
>         num = new
>     }
> }
>  
> var test = Test()
>  
> Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (timer) in
>     print("tick")
>     test.newNum(new: 8)
> }
>  
> Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { (timer) in
>     print("tack, test.num = \(test.num)")
> }
>  
>  
> CFRunLoopRun()
> 
> 
> 
> We have next log:
> tick
> tack, test.num = 8
>  
> Why Timer's two closure return to us value 8 and not 0?


Because the first timer changed the value to 8 when it expired one second before.

> 
> 
> 
> -- 
> Седых Александр
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list