How can I iterate over specific indexes of a given string? Let's say I want to print characters for indexes numbers 2,4,6,8 of a given string.
Note that Swift makes a distinction between indices and offsets. A Collection
guarantees fast access from its Index
, but you usually need to traverse a portion of the collection to access a specific offset. There is an exception where a collection's index is the same as its offset, e.g. Array
.
Back onto the topic, If it's a one-off thing, you can enumerate
the string:
for (offset, character) in string.enumerated() where offset.isMultiple(of: 2) {
...
}
You can change the condition to whatever you'd like. If you do this multiple times, and the condition is non-trivial, you could also convert the string to an Array
.
let array = Array(string)
array[0] = ...
array[2] = ...
...
thank you