我试图掌握Swift的诀窍,并希望了解为什么以下两种方法调用字典,尽管它们产生相同的输出,但据报道,Swift游乐场正在经历不同次数的迭代。
var chocolates = ["Ram's Bladder Cup": 1, "Spring Surprise": 2, "Crunchy Frog": 3]
let chocolatesString = chocolates.reduce("", combine: {$0 + "\($1.0), "})
// The Playground says (4 times)
let newerChocolatesString = chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in
return sum + "\(keyValue.0), "
// The Playground says (3 times)
print(chocolatesString)
print(newerChocolatesString)
// The output from both is however identical and as expected...
我很感激能理解这一点--我可以很明显地看到结果并没有差别,但是我想了解为什么游乐场会有不同的结果。
发布于 2016-01-20 21:58:02
在执行过程中,每当一行代码被“访问”不止一次时,操场就会使用"n次“符号。这是为了代替显示结果,因为执行不止一次的行(或执行了多个语句的行)可能有多个结果。
当关闭机构是在它自己的线,操场报告说,线执行3次。当闭包体位于传递给它的reduce
调用的同一行时,它会说"4次“,因为这一行代码在执行过程中被”访问“了4次--一次是针对reduce
调用本身,另三次是针对闭包体。
注意,无论您使用哪种闭包语法,都会发生这种情况--这完全取决于您在何处放置换行符。
chocolates.reduce("", combine: {
$0 + "\($1.0), " // (3 times)
})
chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in
return sum + "\(keyValue.0), " // (3 times)
}
chocolates.reduce("", combine: {$0 + "\($1.0), "})
// (4 times)
chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in return sum + "\(keyValue.0), "}
// (4 times)
我面前没有Xcode,但是IIRC --即使你用;
在一行上放了多个语句,你也会看到这一点。它与闭包语法无关,与换行vs语句有关:
let a = 1 // 1
let b = a + 1 // 2
let a = 1; let b = a + 1 // (2 times)
发布于 2015-11-14 14:19:31
var chocolates = ["Ram's Bladder Cup": 1, "Spring Surprise": 2, "Crunchy Frog": 3]
let chocolatesString = chocolates.reduce("", combine: {
$0 + "\($1.0), " // (3 times)
})
let newerChocolatesString = chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in
return sum + "\(keyValue.0), "
// The Playground says (3 times)
}
print(chocolatesString)
print(newerChocolatesString)
// The output from both is however identical and as expected...
。。该数字不反映迭代次数,而是反映表达式计算的次数。
https://stackoverflow.com/questions/33711280
复制