Swift中遍历字典获取最大值及对应键时遇到类型错误的求助
Hey there! Let's break down what's going wrong with your code and fix it properly.
First, Let's Identify the Errors
Your error error: cannot call value of non-function type '[String : [Int]]' stems from two key mistakes:
Unnecessary inner loop: The
for name in namesloop is totally redundant here.namesis a single string (the dictionary's key, like "Prime" or "Fibonacci"), so looping over it would iterate through each character of the string—this isn't what you want at all.Incorrect dictionary access: You tried to call
interestingNumbers(forKey: largest)like a function, butinterestingNumbersis a dictionary. Dictionaries use subscript syntax ([]) to access values, but even that's unnecessary here. The key corresponding to the current number set is already stored in thenamesvariable from your outer loop!
Corrected Code
Here's the fixed version of your code with clarifying comments:
let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 var largestName: String? // Iterate over each (key, value) pair in the dictionary for (category, numbers) in interestingNumbers { // Iterate over each number in the current category's array for number in numbers { // No extra loop needed—we already have the category name if number > largest { largest = number // Assign the current category name directly largestName = category } } } print(largest) // Output: 25 print(largestName) // Output: Optional("Square")
A More Swift-idiomatic Approach (Optional)
If you want to make this code more concise, you can use Swift's higher-order functions like reduce to achieve the same result with cleaner syntax:
let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] // Use reduce to accumulate the maximum value and its corresponding key let result = interestingNumbers.reduce(into: (key: String?, maxValue: 0)) { partialResult, entry in if let currentMax = entry.value.max(), currentMax > partialResult.maxValue { partialResult.key = entry.key partialResult.maxValue = currentMax } } print(result.maxValue) // Output: 25 print(result.key) // Output: Optional("Square")
This version uses reduce to track the running maximum, and leverages the built-in max() method on arrays to get the largest number in each category without manual looping.
内容的提问来源于stack exchange,提问作者Mirella Candy

