Need help Exercise Partial Iteration (Swift playground)

Hi! Here is an exercise, and I can't figure out how to do it.

Answered by Claude31 in 726945022

You were nearly there.

Problem here is that if no message contains "Caterpillar", app will crash because index will be out of bounds.

2 ways:

With while loop:

var index: Int = 0
var foundMessage: Bool = false

while !foundMessage && index <  aliceMessages.count {
    foundMessage = aliceMessages[index].contains("Caterpillar")
    if !foundMessage {
       index += 1
  }
}
print(index)

Or with for

var index: Int = 0

for message in aliceMessages {
 if message.contains("Caterpillar") { 
      print(index, message)
      break // We leave the loop
  }
  index += 1
}

Please show what you have tried for the for loop.

Hint: it should be something like this pseudo code:

for message in aliceMessages {
 if found character {  // Write real code here
      print(message)
      break // We leave the loop
  }
}

I tried it like this:

var index: Int = 0
var foundMessage: Bool = false

while foundMessage == false {
    foundMessage = aliceMessages[index].contains("Caterpillar")
    index += 1
    if foundMessage {
        print()
    }
}
print(index - 1)

But I don't think that it should look like this. Also it should've been written with while loop, so it cannot be done by for in with break.

Accepted Answer

You were nearly there.

Problem here is that if no message contains "Caterpillar", app will crash because index will be out of bounds.

2 ways:

With while loop:

var index: Int = 0
var foundMessage: Bool = false

while !foundMessage && index <  aliceMessages.count {
    foundMessage = aliceMessages[index].contains("Caterpillar")
    if !foundMessage {
       index += 1
  }
}
print(index)

Or with for

var index: Int = 0

for message in aliceMessages {
 if message.contains("Caterpillar") { 
      print(index, message)
      break // We leave the loop
  }
  index += 1
}
var messageIsFound = false
var index = 0

while !messageIsFound {
    messageIsFound = aliceMessages[index].contains("Caterpillar")
    if messageIsFound {
        print("\(index): \(aliceMessages[index])")
    }
    index += 1
}

Hey Claude31,

Thank you for being active and answering the questions! I saw your response after I wasn't able to figure it out, and it was really helpful.

However, after I copy-pasted your code, I saw that if the while loop does NOT find a match, the code will simply print the index value in the end, which isn't helpful.

So I re-wrote your code and would like your opinion:

var index = 0
var found = false
let totalPlayTime = aliceMessages.count
 
while found == false && index < aliceMessages.count {
    found = aliceMessages[index].contains("Alice")
    if found == false {
      index += 1
  } else if found == true {
    print ("Found at index number \(index), after about \((index*100)/(totalPlayTime))% of the play is over.")
  }
}
if index >= aliceMessages.count - 1 {
  print("No matches")
}

I'm sure it can be made even better by making this into a re-usable function, but right now I don't feel like over-engineering this. :P What do you think?

Best, Aradroid.

I'm sure it can be made even better by making this into a re-usable function

Just FYI, the standard library has a lot of these algorithms built in. For example:

let words = ["Hello", "Cruel", "World!"]
words.contains("Cruel")                         // true
words.contains("Goodbye")                       // false
words.contains(where: { $0.contains("o") })     // true
words.contains(where: { $0.contains("z") })     // false
words.firstIndex(of: "Cruel")                   // 1
words.firstIndex(of: "Goodbye")                 // nil
words.firstIndex(where: { $0.contains("o") })   // 0
words.firstIndex(where: { $0.contains("z") })   // nil
words.filter( { $0.contains("o") } )            // ["Hello", "World!"]
words.allSatisfy( { $0.count >= 5 } )           // true
words.allSatisfy( { $0.contains("o") })         // false

These days I rarely find myself writing a loop because most loops can be expressed in terms of these built-in algorithms.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Need help Exercise Partial Iteration (Swift playground)
 
 
Q