Start learning free

LESSON 109 OF 415 · DICTIONARIES

Dictionary Length in Swift: count and isEmpty

Lesson Read the full explanation

In Swift, you can get the number of key-value pairs in a Dictionary using the .count property:

var scores: [String: Int] = [:]
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72

let count = scores.count
print(count)  // 3

.count returns the number of entries. You can also check if it's empty with .isEmpty:

print(scores.isEmpty)  // false
var empty: [String: Int] = [:]
print(empty.count)     // 0

Assignment
Follow the Coding Tutorial and get the number of entries in scores!


Hint
Use scores.count and assign it to count.

STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · DICTIONARIES

    Dictionary Length in Swift, explained

    Counting entries with count

    The count property of a dictionary is the number of key-value pairs it holds. It is a property, not a method, so you write scores.count with no parentheses.

    var scores: [String: Int] = [:]
    scores["Alice"] = 95
    scores["Bob"] = 87
    scores["Charlie"] = 72
    
    let count = scores.count
    print(count)
    
    3
    

    Each pair counts once. The keys alone and the values alone have the same number of elements, so scores.keys.count and scores.values.count are 3 as well.

    Checking for empty

    To ask whether there are any entries at all, use isEmpty. It reads better than comparing count with 0:

    print(scores.isEmpty)
    let empty: [String: Int] = [:]
    print(empty.count)
    print(empty.isEmpty)
    
    false
    0
    true
    

    How the count changes

    The count follows the operations from the earlier lessons:

    • Assigning to a new key adds a pair, so the count goes up by one.
    • Assigning to an existing key replaces the value, so the count stays the same.
    • Assigning nil to a key removes the pair, so the count goes down by one if the key was there.
    scores["Dan"] = 60
    print(scores.count)
    scores["Alice"] = 100
    print(scores.count)
    scores["Bob"] = nil
    print(scores.count)
    
    4
    4
    3
    

    Because keys are unique, a dictionary literal with a repeated key is a mistake, and the program stops at run time when it is created. Build dictionaries from distinct keys.

    Counting things with a dictionary

    A common use of count is to see how many distinct items a dictionary has collected. Here a dictionary counts how often each character occurs in a string, and the number of entries is the number of distinct characters:

    var counts: [Character: Int] = [:]
    for ch in "hello" {
        counts[ch, default: 0] += 1
    }
    print(counts["l"]!)
    print(counts.count)
    
    2
    4
    

    The word has five letters, but "l" appears twice, so there are four distinct keys. This is the difference between the size of the input and counts.count.

    Removing a key also lowers the count, and the original is unaffected by removals on a copy: after var s = scores and s.removeValue(forKey: "Bob"), s.count is one less than scores.count.

    Same name, same idea as arrays

    Arrays also use count and isEmpty, so the habit carries over. For an array it counts elements, and for a dictionary it counts pairs. For [95, 87, 72] the count is 3, the same as for ["Alice": 95, "Bob": 87, "Charlie": 72]. Strings use count too, and it counts characters.

    The exercise

    The starter code gives a dictionary named scores with three students. One step is needed:

    1. Declare a constant count with let and assign it scores.count.
    var scores: [String: Int] = ["Alice": 95, "Bob": 87, "Charlie": 72]
    
    let count = scores.count
    

    The constant holds 3, the number of pairs. It is a snapshot: if the dictionary changes later, count keeps the old number, and you read scores.count again to get the new one.

    Common mistakes

    • Adding parentheses. scores.count() does not compile, because count is a property.
    • Using length or size. Other languages use those names. Swift uses count, and a dictionary has no property called length, so the compiler reports an error.
    • Confusing the count with a value. scores.count is 3 even though the scores themselves are 95, 87 and 72.

    Key takeaways

    • dict.count is the number of key-value pairs.
    • dict.isEmpty tells you whether there are none.
    • Adding a new key raises the count, replacing a value does not, and removing a key lowers it.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free