Problem overview
The function toDictionary receives an array of strings, names, and an array of integers, scores, of the same length. It returns a dictionary in which each name is a key and the score at the same index is its value. The names are all different, two names may have the same score, and empty arrays give an empty dictionary.
For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the result pairs Ana with 90, Ben with 75 and Cara with 88.
Approach: one index reaches both
A name and its score share a position, so a single loop index i can read names[i] and scores[i] together. For each index, one assignment adds the pair to the dictionary. No lookups or checks are needed, because the names are all different and no key is ever written twice.
Step by step
- Create
resultas an empty[String: Int]withvar. - Loop over the indices with
for i in 0..<names.count. - Store the pair:
result[names[i]] = scores[i]. - Return
resultafter the loop.
Tracing the example: at i = 0 the dictionary gets "Ana" with 90. At i = 1 it gets "Ben" with 75, and at i = 2 "Cara" with 88. The loop stops because the range ended, and the function returns the three entries.
This works because the two arrays are parallel: the same position in each describes the same person. The lesson doesn't need to check that the lengths match, since it promises they do. If scores were shorter than names, reading scores[i] past the end would crash.
The solution in Swift
class Solution {
func toDictionary(_ names: [String], _ scores: [Int]) -> [String: Int] {
var result = [String: Int]()
for i in 0..<names.count {
result[names[i]] = scores[i]
}
return result
}
}
Swift details
0..<names.countis a half-open range: it includes 0 and stops beforenames.count. For three names it covers 0, 1 and 2, exactly the valid indices. For an empty array the range0..<0is empty, so the loop body never runs and the function returns an empty dictionary.- Assignment adds or replaces. Assigning to a key through a subscript inserts the entry when the key is new, and replaces the value when the key exists. Here every key is new.
- Different types on each side. The keys are
Stringand the valuesInt, matching the function's return type[String: Int]. - The alternative. Swift has
Dictionary(uniqueKeysWithValues: zip(names, scores)), which does the whole job in one expression. The lesson builds the dictionary with a loop to practise the index and the subscript assignment.
Edge cases and common mistakes
- Same score twice.
["Zoe", "Adam"]with[60, 60]gives two entries. Equal values are fine; only keys must be unique. - Empty input. Two empty arrays give
[:], the empty dictionary. - A single pair.
["Max"]and[100]give one entry. - Using
0...names.count. The closed range includesnames.count, one past the last index, and readingnames[names.count]crashes the program. - Repeated names. If a name appeared twice, the later score would overwrite the earlier one. The lesson guarantees this doesn't happen.
Testing
Entries are listed in alphabetical order here for readability.
["Ana", "Ben", "Cara"]with[90, 75, 88]gives Ana: 90, Ben: 75, Cara: 88.["Zoe", "Adam"]with[60, 60]gives Adam: 60, Zoe: 60.["Max"]with[100]gives Max: 100.[]with[]gives[:].
