Start learning free

LESSON 104 OF 349 · DICTIONARIES

Dictionary Length in Swift 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

    Dictionary Length in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free