Hi there! I'm stuck. aliceMessages array is just a really long conversation. Here is the exercise (17th page of Arrays and Loops lesson):
Create a for…in loop to process the aliceMessages array by iterating through its legal indices. In the body of the loop, use the index to access a message from the array and check whether it contains the string "Caterpillar". If the message refers to the Caterpillar, print it to the console, along with its index. This process is called a linear search. Linear search is a common algorithm for processing arrays by examining its contents in order and evaluating each item to determine whether it meets certain criteria
Thanks for your help!
You were nearly there:
for messageNumber in 0 ... aliceMessages.count - 1 {
if aliceMessages.contains("Caterpillar") {
print("\(messageNumber): \(aliceMessages[messageNumber])")
}
}
But:
- aliceMessages.contains tests for exact match:
- I created this test:
let aliceMessages = ["A Caterpillar", "other machine"]
if aliceMessages.contains("Caterpillar") { print("OK") } else { print("aliceMessages Does not contain Caterpillar")}
if aliceMessages.contains("A Caterpillar") { print("OK A") }
You get
aliceMessages Does not contain Caterpillar
OK A
- Reason is when you test aliceMessages.contains("Caterpillar"), you test for exact match in the array, for for item containing the word.
Just change forfor messageNumber in 0 ... aliceMessages.count - 1 {
if aliceMessages[messageNumber].contains("Caterpillar") {
print("\(messageNumber): \(aliceMessages[messageNumber])")
}
}
And you get
0: A Caterpillar