Junior — Middle
Millised on erinevused massiivide ja stringide töötlemisel tsüklite kasutamisel iteratsiooniks?
sobes.tech AI
Vastus AI-lt
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. During iteration, you get each element as a separate object with which you can work 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 combined emoji).
Example of iterating over an array:
let numbers = [1, 2, 3]
for number in numbers {
print(number)
}
And over a string:
let text = "Привет"
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 combined, and simple indexing may be inefficient or incorrect. An array has a fixed type, and indexing is simpler.