You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中遍历字典获取最大值及对应键时遇到类型错误的求助

Fixing Your Dictionary Traversal & Max Value Issue

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:

  1. Unnecessary inner loop: The for name in names loop is totally redundant here. names is 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.

  2. Incorrect dictionary access: You tried to call interestingNumbers(forKey: largest) like a function, but interestingNumbers is 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 the names variable 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:04:07