Group Group Group Group Group Group Group Group Group

Programming in Swift: Fundamentals · Challenge: Iterating Collections | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5539282-programming-in-swift-fundamentals/lessons/23

I was wondering why in the if loop , I can’t use pastry.startIndex == “c” instead of pastry[pastry.startIndex] == “c” , Im not sure why inside the [ ] theres pastry.startIndex I thought that inside the brackets you only put the position index , how is pastry.startIndex a position? doesn’t that return the first character?

for pastry in pastries
{
if pastry[pastry.startIndex] == “c”
{
print(pastry)
}

}

I had the same question as you. I guess this is how swift works with Strings. Swift documentation says that

different characters can require different amounts of memory to store, so in order to determine which Character is at a particular position, you must iterate over each Unicode scalar from the start or end of that String . For this reason, Swift strings can’t be indexed by integer values.

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

You can use subscript syntax to access the Character at a particular String index.

  1. let greeting = “Guten Tag!”
  2. greeting[greeting.startIndex]
  3. // G
  4. greeting[greeting.index(before: greeting.endIndex)]
  5. // !
  6. greeting[greeting.index(after: greeting.startIndex)]
  7. // u
  8. let index = greeting.index(greeting.startIndex, offsetBy: 7)
  9. greeting[index]
  10. // a
1 Like

Hey folks! These are good questions and insights. Swift is a bit weird when it comes to Strings.

While you can use the .first instance property of a Swift String to get the first character of a string, you’ll have to remember that pastry.first will return an Optional – that means Swift can’t guarantee that there is a first character (i.e, the string may be empty).

So you’d just have to be aware of that and unwrap the value of pastry.first as an Optional (by force-unwrapping or, better still, with a default value) if you want to use pastry.first here.

I’m on the same section, how would you check your string array for items with a capital “C” so it’s indifferent to case?
I found this options: .caseInsensitive but how to implement?

For challenge 1 I used pastry.starts(with: "c") and got the desired result. Is there an advantage or disadvantage to using this method?

Hey @trose618 , for this example there’s no real difference - good solution with starts(with:).