Last active
May 27, 2016 08:01
-
-
Save lukaskollmer/69b6d615776417b673fbf4f0371be054 to your computer and use it in GitHub Desktop.
How do languages handle removing objects during iteration?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var list = [1, 2, 3, 4]; | |
list.forEach(function(entry) { | |
console.log(entry); | |
var index = list.indexOf(entry); | |
list.splice(index, 1); | |
}); | |
console.log('list after loop: ', list); | |
/** | |
Console output: | |
> 1 | |
> 3 | |
> list after loop: [2, 4] | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSMutableArray<NSNumber *> *list = [[NSMutableArray alloc] initWithArray:@[@(1), @(2), @(3), @(4)]]; | |
[list enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { | |
NSLog(@"object: %@", obj); | |
[list removeObject:obj]; | |
}]; | |
NSLog(@"list after loop: %@", list); | |
/** | |
Console output: | |
> object: 1 | |
> object: 3 | |
> list after loop: ( | |
2, | |
4 | |
) | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var list: [Int] = [1, 2, 3, 4] | |
for (index, object) in list.enumerate() { | |
print(object) | |
list.removeAtIndex(index) | |
} | |
print("list after loop: \(list)") | |
/** | |
Console output: | |
> 1 | |
> 2 | |
> 3 | |
> fatal error: Index out of range | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment