Start learning free

LESSON 128 OF 678 · DICTIONARIES

Dictionary Length in Swift

Lesson

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