简体   繁体   English

如何在Swift中获取初始的闭包变量?

[英]How can I get initial closure variable in Swift?

I want to access the value of a variable from inside a closure. 我想从闭包内部访问变量的值。 But I don't want to get the changed variable, I want to get the value from the initial closure init. 但是我不想获取更改后的变量,我想从初始关闭init中获取值。

In Objective-C there was no problem with that, because every "outside" variable was copied and could be accessed like a const . 在Objective-C中,这没有问题,因为每个“外部”变量都被复制并且可以像const一样进行访问。 Now every variable behaves like a __block var. 现在,每个变量的行为都类似于__block var。

-- EDIT -- -编辑-

i created a much simpler example. 我创建了一个简单得多的示例。 the one in objective c works, the one in swift not: 目标c中的一项有效,但迅速中的一项无效:

swift: 迅速:

var myQueue: dispatch_queue_t  = dispatch_queue_create("com.mycompany.myqueue", DISPATCH_QUEUE_CONCURRENT);
for i in 0...200 {
    let startDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: (i+1)*(-1), toDate: NSDate.date(), options: NSCalendarOptions.MatchFirst)

    dispatch_async(myQueue, {
        println("\(i) - \(startDate.descriptionWithLocale(NSLocale.systemLocale()))")
        })
}

Output swift (data "bullshit"): 快速输出(数据“ bullshit”):

3 - 2014 M07 30, Wed 17:33:58 GMT+02:00
...
9 - 2014 M07 24, Thu 17:33:58 GMT+02:00
10 - 2014 M07 23, Wed 17:33:58 GMT+021:30 0-
1 12 0-11 442  0-M1 0427 0 1M12201410 76 7,-  M   2-0-S22 7 u0,2 2n1 010 4T1911 u4,

objective c: 目标c:

for (int i = 0; i < 200; i++) {
    NSDate *startDate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay value:(i+1)*(-1) toDate:[NSDate date] options:NSCalendarMatchFirst];

    dispatch_async(myQueue, ^(void) {
        NSLog(@"%d - %@", i, startDate);
    });
}

objective c output: 目标c输出:

2014-08-03 17:30:49.893 m7[92781:611495] 1 - 2014-08-01 15:30:49 +0000
2014-08-03 17:30:49.893 m7[92781:611494] 3 - 2014-07-30 15:30:49 +0000
2014-08-03 17:30:49.894 m7[92781:611496] 4 - 2014-07-29 15:30:49 +0000
2014-08-03 17:30:49.894 m7[92781:611498] 6 - 2014-07-27 15:30:49 +0000
2014-08-03 17:30:49.894 m7[92781:611497] 5 - 2014-07-28 15:30:49 +0000
2014-08-03 17:30:49.895 m7[92781:611495] 9 - 2014-07-24 15:30:49 +0000
...

I want to access startDate within the closure. 我想在闭包内访问startDate But it's the changed value and not the inital one, from before the closure was executed. 但这是执行关闭之前的更改后的值,而不是初始值。

What can I do? 我能做什么?

Just use local variables for start/endDate in the loop: 只需在循环中为start / endDate使用局部变量

for i in 0...6 {
    let startDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: (i+1)*(-1), toDate: today, options: NSCalendarOptions.MatchFirst)
    let endDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: (i)*(-1), toDate: today, options: NSCalendarOptions.MatchFirst)

    self.stepCounter.queryStepCountStartingFrom(startDate, to: endDate, toQueue: NSOperationQueue.mainQueue(), withHandler: {
        (numberOfSteps: NSInteger , error: NSError!) in
        println("steps: \(numberOfSteps)")
    })
}

Then each iteration has its own instance of the dates, and the value of the captured dates does not change. 然后,每个迭代都有其自己的日期实例,并且捕获的日期的值不会更改。

Update: Another problem is that the Swift println() function is not thread-safe. 更新:另一个问题是Swift println()函数不是线程安全的。 That causes the garbage in your example. 这会在您的示例中造成垃圾。 For debug output from concurrently running threads, better use NSLog() which is available in Swift as well: 对于并发运行的线程的调试输出,最好使用Swift中也提供的NSLog()

dispatch_async(myQueue, {
    NSLog("%d - %@", i, startDate)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM