Mix Tape

Can someone explain how the below code works, cause the explanation about the two sides of the mixtape got me confused a little bit.

print(“Side A\n”)

for i in 0 …< mixtape.count/2 { // this part and the part after this I don’t get
print("(i+1). (mixtape[i])")
}

print()

// ======
// Side B
// ======
print(“Side B\n”)

for i in mixtape.count/2 …< mixtape.count { // This part and the part after this I don’t get
print("(i+1). (mixtape[i])")
}

print()

1 Like
for i in 0 …< mixtape.count/2 { 
    print("(i+1). (mixtape[i])")
}

Couple of points:

  • for-loops iterate from a starting point to an end point.
  • you can think of i as the iterated item (first it’s 0, then it’s 1, then it’s 2)
  • starting point is: 0
  • ending point is mixtape.count/2. Half the size of the total mixtape count.
  • < means that the endpoint will not be included in the iteration. So 0…<5 excludes 5, but 0…5 will include 5.
  • the print statement is in two parts, the counter, and the item accessed
  • the counter has a plus one because we begin counts at 1 (unlike machines)
  • mixtape[i] accesses the item at index i of the mixtape list.

Welcome to the forums! :saxophone: :saxophone: Remember to format with the </> in the future. It helps everyone get you the best answer the quickest.

Additionally, the swift documentation gives very neat and clear examples as to how to deal with different scenarios, check it out!

https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html

1 Like

Thank you so much for the explanation I understood it perfectly, I was a bit stuck with the 0…<5 stuff as it is not mentioned in the lesson but googling and with your help it made sense. Thank you again be safe and happy coding :slight_smile:

1 Like

great answer @toastedpitabread! love the saxphones too :slight_smile:

1 Like