Cannot convert value of type 'Int' to expected argument type 'Dictionary.Index'

跟風遠走 提交于 2021-02-17 05:17:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!