Swift: How to iterate through all elements in an Array, Set or Dictionary

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.


// create an Array
var someArray = ["one", "two", "three", "four"]

// access a single item (starts at 0)

// iterate over every item in the array
for items in someArray {


// create a set
var mySet: Set = ["one", "two", "three", "four"]

// iterate over all items in the set
for item in mySet {

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.


// create a dictionary
var myDictionary = [
    "First": 1,
    "Second": 2,
    "Third": 3]

// access a single item

// 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:

        // 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:

        // 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:

        // 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]);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.