Looping through all elements in Arrays, Sets and Dictionaries is fairly straightforward in Swift: we can use Fast Enumeration using a for-in loop. Here are three quick examples to demonstrate this.
I’ve also included how to access one specific element in either collection.
Arrays
1 2 3 4 5 6 7 8 9 10 |
// create an Array var someArray = ["one", "two", "three", "four"] // access a single item (starts at 0) print(someArray[3]) // iterate over every item in the array for items in someArray { print(items) } |
Sets
1 2 3 4 5 6 7 |
// create a set var mySet: Set = ["one", "two", "three", "four"] // iterate over all items in the set for item in mySet { print(item) } |
Just as a reminder: a Set is more or less the same as an Array, with the exception that this collection has no order. Whilst iterating over an Array will always show the first item first, the order of a Set is unpredictable. Fetching a Set is slightly faster than an Array.
Dictionaries
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// create a dictionary var myDictionary = [ "First": 1, "Second": 2, "Third": 3] // access a single item print(myDictionary["First"]) // iterate over all keys for (key, value) in myDictionary { print("Key: \(key) - Value: \(value)") } |
Compared to Objective-C
To achieve the same thing in Objective-C, a bit more code is necessary. Just to remind ourselves, here’s how to iterate through an NSArray:
1 2 3 4 5 6 7 8 9 10 11 |
// create an array NSArray *myArray = @[@"one", @"two", @"three", @"four"]; // access a single item NSString *arrayValue = [myArray objectAtIndex:2]; NSLog(@"Single Value: %@", arrayValue); // iterate over all items in the array for (id value in myArray) { NSLog(@"Value: %@", value); } |
Likewise, here’s how Fast Enumeration works for an NSDictionary:
1 2 3 4 5 6 7 8 9 10 11 |
// create a dictionary NSDictionary *myDictionary = @{@"First": @1, @"Second": @2, @"Third": @3}; // access a single item NSLog(@"%@", [myDictionary objectForKey:@"First"]); // iterate over all items for (id key in myDictionary) { NSNumber *currentValue = [myDictionary valueForKey:key]; NSLog(@"Key: %@ - Value: %@", key, currentValue); } |
And of course for NSSets too:
1 2 3 4 5 6 7 8 |
// create a Set NSArray *someArray = @[@"one", @"two", @"three", @"four"]; NSSet *mySet = [[NSSet alloc]initWithArray:someArray]; // iterate over all items in the NSSet for (id item in mySet) { NSLog(@"%@", [item description]); } |