问题
i am getting the error "Cannot convert value of type 'Int' to expected argument type 'Dictionary.Index'" at lines 8 & 9 ("let k" & "for y in")
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()
}
回答1:
Not every collection in Swift is indexed by Int. You should always use the collection indices when iterating your collections. Note that using a single letter to represent a variable in Swift it is not good practice unless you are using something like (x,y) for coordinates:
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)
}
}
}
}
or simply using high order methods:
func checkFavoriteCount(table: UITableView) {
favArray = namesDictionary.flatMap(\.value).filter(\.isFav)
// or filtering while flattening
// favArray = namesDictionary.flatMap { $0.value.filter(\.isFav) }
}
来源:https://stackoverflow.com/questions/66164950/cannot-convert-value-of-type-int-to-expected-argument-type-dictionary-index