Reputation: 2433
What is difference b/w enumerator and iterator in Swift or Objective C? Please explain and give some example of enumerator and iterator. An interviewer asked me but I could not explain. Is enumerator means Enum or iteration over collection?
As per my understating iterator performs iteration/looping over collection. e.g forEach, for loop, while, do while etc. But I do not what is enumerator.
Upvotes: 0
Views: 482
Reputation: 441
I would like to add one more point to the above answer. In Obj C, while using enumerator, we can't update the collection while we are looping, but we can do it with Iterator.
NSMutableArray *arr = [NSMutableArray arrayWithArray:@[@1,@2,@3,@4,@5]];
// Enumeration
for (NSString *st in arr) {
[arr removeObjectAtIndex:1]; *//Error: Collection was mutated while being enumerated.*
}
// Iteration
for (int i=0; i<arr.count; i++) {
[arr removeObjectAtIndex:1];
}
Result:
[1, 3, 4, 5]
[1, 4, 5]
[1, 5]
For Swift c style for loop has been deprecated, and in the 'for in' loop we can update the collection but it loops for initial array count number of times
var arr = [1,2,3,4,5,6,7]
for i in arr {
if arr.count > 3 {
arr.remove(at: 3)
}
print(arr)
}
Result:
[1, 2, 3, 5, 6, 7]
[1, 2, 3, 6, 7]
[1, 2, 3, 7]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
Upvotes: 0
Reputation: 53000
The distinction between the two in programming is not always large and you'll find cases where the words are used interchangeably, however they do describe something different. You wrote:
As per my understating iterator performs iteration/looping over collection. e.g forEach, for loop, while, do while etc. But I do not what is enumerator.
The key point of iteration is just "iteration/looping" – simply repeating something, e.g. the Newton-Raphson method is an iterative algorithm for approximating a square-root and is typically implemented in a programming language using a loop.
Enumeration is listing things out, that's where your "over collection" comes from. So the for
/in
loop (an iterative construct) enumerates a collection. The standard collections all provide enumerators which return NSEnumerator
objects, and you typically, but not always, would use these in an iterative construct to process the collection.
Enumerated types, enum
's, are so called because they list out all the values, i.e. enumerate them.
So your interviewer might have been expecting you to state that iteration is supported in Swift/Objective-C by the iterative statements of the languages (for
, while
etc.), while enumeration is provided by objects/methods which either return each item in turn (e.g. NSArray
's objectEnumerator
) or which process each element in turn (e.g. NSArray
's enumerateObjectsUsingBlock:
). The for
/in
combines these two, it is an iterative construct which directly uses an object enumerator rather than requiring the programmer to use the enumerator directly.
HTH
Upvotes: 1