Swift: dictionary access via index

前端 未结 4 1890
不知归路
不知归路 2021-02-05 10:54

I want to use values from a dictionary in my UITableViewCells. Can I get those from a dictionary by using indexPath.row for the value and indexPath.section for the key?

4条回答
  •  轮回少年
    2021-02-05 11:20

    Here is my small trick to access Dictionary by index. Just wrap dictionary!

    var dict = [String: [Int]]()
    
    dict.updateValue([1, 2, 3], forKey: "firstKey")
    dict.updateValue([3, 4, 5], forKey: "secondKey")
    
    var keyIndex = ["firstKey": "firstKey", "secondKey": "secondKey"]
    var arr = [[String: [Int]]]()
    
    for (key, value) in dict {
        arr.append([keyIndex[key]!: value])
    }
    
    print(arr[0]) // ["firstKey": [1, 2, 3]]
    

提交回复
热议问题