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

Седых Александр se-a at mail.ru
Wed Nov 30 04:38:40 CST 2016


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
     mutating func 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?


-- 
Седых Александр
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161130/178c2f7d/attachment.html>


More information about the swift-users mailing list