swift playground 中的 for-in 循环只计算循环次数,不打印

swift for-in loop in playground just counts loops, does not print

刚开始使用 Swift,查看 the Wikipedia article,它有以下代码:

// Define a dictionary with four items:
// Each item has a person's name and age
let people = ["Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25]

// Now we use Swift's flexible enumerator system
// to extract both values in a single loop
for (name, age) in people {
 print("\(name) is \(age) years old.")
}

把它放到 XCode 的操场上,我希望它能看到这个:

Anna is 67 years old.
Beto is 8 years old.

等等

相反,在右侧面板中,它只显示:

(4 times)

最右边有一个按钮,在 (4 times) 之外,当我单击它时,会导致 Jack is 33 years old. 在循环中显示。 (请参见下面的屏幕截图。)再次单击该按钮,它就会消失。谁能帮我理解这一切背后的逻辑?

您的代码中存在一个小问题,您应该包含一个参数“\(name)”而不是 (name) 以便打印它。所以你应该这样使用

for (name, age) in people {
    print("\(name) is \(age) years old.")
}

如果您想显示问题中所问的所有值,只需按照以下步骤操作即可:-

**Step 1**

点击右边的+号corner.Then它显示最新的值。

步骤 2

如果要显示所有值,请单击最近的值并右键单击并选择值历史记录

步骤 3

然后你可以看到所有的值。

您缺少的是所谓的字符串插值。因此,要通过将 variable/constant 的值与字符串连接来打印它,您必须这样做。

print("\(name) is \(age) years old.")

其次你必须按(⇧⌘Y)才能在调试区看到输出