So my task is to only print even indexed characters using for-in loop.
Create a for-in loop that will loop through alphabet. Inside the loop, print every other letter by continuing to the next iteration if you are on a letter you do not wish to print. (Hint: You can use the isMultiple(of:) method on Int to only print even indexed characters).
Here’s my code:
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in alphabet {
if letter == "F" { // letter I wish not to print
continue
}
// How do I need to use isMultiple(of: ) method?
print(letter)
}
3
Answers
I found out, that we need to put 'print' statement inside 'if' statement, because it will print even indexes (what task says).
But if we put 'continue' inside if statement, we will skip even indexes. So the odd ones will be printed. Am I right?
Here’s how you can do it.
The swifty way is
enumerated()
– to get indexed characters – in conjunction with awhere
clause.The
where
clause skips the current iteration if the condition isfalse
.This prints "A C E …"