Search code examples
xcodeswiftenumsenumerator

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


Just getting started with Swift, looking at the Wikipedia article, it has this code:

// 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.")
}

Putting this into a playground in XCode, I expected this to see this:

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

etc.

Instead, in the right-hand panel, it just shows this:

(4 times)

There is a button over on the far right, beyond the (4 times) which, when I click it, causes Jack is 33 years old. to display within the loop. (See screen shot below.) Click the button again, and that disappears. Can anyone help me understand the logic behind all this?

for-in mystery


Solution

  • Small issue in your code you should include a parameter "\(name)" not (name) in order to print it. so you should use like this

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

    If you want to show all the value as you asked on question just follow these steps :-

    **Step 1**
    

    Clicks the + sign right corner.Then it shows latest value. enter image description here

    Step 2

    If you want to show all the values clicks the recent value and right click and choose value history

    enter image description here

    Step 3

    Then you can see the all values.

    enter image description here