我得到错误“无法将类型‘Int’的值转换为预期的参数类型‘Dictionary’。第8行的索引' '
var namesDictionary = [String: [classObject]]()
func checkFavoriteCount(table:UITableView)
{
favArray.removeAll()
for x in (0...namesDictionary.keys.count - 1)
{
let k = namesDictionary[x].key
for y in (0...namesDictionary[x].value.count - 1)
{
if (namesDictionary[k]?[y].isFav ?? false)
{
favArray.append((namesDictionary[k]?[y])!)
}
}
}
tableView.reloadData()
}
并非Swift中的每个集合都由Int索引。迭代集合时,应该始终使用集合索引。请注意,在Swift中使用单个字母表示变量并不是一种好的做法,除非您使用类似(x,y)的坐标:
func checkFavoriteCount(table: UITableView) {
favArray.removeAll()
for index in namesDictionary.indices {
let key = namesDictionary[index].key
for valueIndex in namesDictionary[index].value.indices {
if let object = namesDictionary[key]?[valueIndex], object.isFav {
favArray.append(object)
}
}
}
}
或者简单地使用高阶方法:
func checkFavoriteCount(table: UITableView) {
favArray = namesDictionary.flatMap(\.value).filter(\.isFav)
// or filtering while flattening
// favArray = namesDictionary.flatMap { $0.value.filter(\.isFav) }
}