Junior — Middle
What are the differences between processing an array and a string when using loops for iteration?
sobes.tech AI
Answer from AI
When iterating over an array and a string in iOS (for example, in Swift), there are some differences related to data types and their structure.
-
Array — a collection of elements of the same type. When iterating, you get each element as a separate object that can be worked with directly.
-
String — a sequence of characters (Character). In Swift, a string is a collection of characters, but each character can be complex (for example, a composite emoji).
Example of iterating over an array:
let numbers = [1, 2, 3]
for number in numbers {
print(number)
}
And over a string:
let text = "Hello"
for char in text {
print(char)
}
The main difference is that when working with a string, it is important to consider that characters can be composite, and simple indexing may be inefficient or incorrect. An array has a fixed type and simpler indexing.