Swift Dictionary.reduce() - 使用完整语法和短语法报告的不同迭代次数

时间:2015-11-14 17:34:50

标签: swift swift-playground

我试图了解Swift,并希望了解为什么下面两个方法调用一个Dictionary,虽然它们产生相同的输出,但据报道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...

我非常感谢理解这一点 - 我可以清楚地看到结果没有区别,但我想了解为什么Playground会报告差异。

2 个答案:

答案 0 :(得分:3)

游乐场使用" n次"每当一行代码被访问时#not;#34;执行期间不止一次。发生这种情况代替显示结果,因为执行了多次的行 - 或者执行了多个语句的行 - 可以有多个结果。

当封闭体在自己的线上时,操场报告该线执行了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你也会看到这个。它与闭包语法无关,也与换行符与语句有关:

let a = 1 // 1
let b = a + 1 // 2

let a = 1; let b = a + 1 // (2 times)

答案 1 :(得分:0)

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...

..数字并不反映迭代次数,它反映了表达式评估的数量