How to avoid duplicate key error in swift when iterating over a dictionary

后端 未结 3 1529
日久生厌
日久生厌 2021-01-18 03:43

I\'m practicing swift and I\'m trying to iterate over a Dictionary to print the key, but it gives me a

fatal error: Dictionary literal contains dupli

相关标签:
3条回答
  • 2021-01-18 04:34

    As others already said, you cannot create a dictionary where the same key does appear more then once.

    That said I really like solution provided by luk2302 because if does offer a well structured approach.

    Here I am just adding another solution.

    Since the real information in your (wrong) dictionary is the value (not the key) what's the meaning of using a Dictionary?

    You could simply use an array

    let ages = [14, 15, 75, 43, 103, 87, 12]
    ages.forEach { print($0) }
    
    0 讨论(0)
  • 2021-01-18 04:40

    Each dictionary key MUST be unique

    let people = ["age1":14, "age2":15, "age3":75, "age4":43, "age5":103, "age6":87, "age7":12]
    for (key, value) in people {
        print(value)
    }
    
    0 讨论(0)
  • 2021-01-18 04:42

    Create a People struct or class and use instances of that in an array rather than a dictionary:

    struct Person {
        var age : Int
    }
    
    let people = [Person(age: 14), Person(age: 15)] // and so on
    
    for person in people {
        print(person)
    }    
    

    A dictionary is a mapping of a unique key to some value. Therefore what you previously did was not working because your key age was not unique. You can however use a different dictionary:

    let people = [14: Person(age: 14), 15: Person(age: 15)] // and so on
    
    for (key, value) in people {
        print("\(key) => \(value)")
    }
    
    0 讨论(0)
提交回复
热议问题