Search code examples
swiftswift-playgroundswift-dictionary

Swift Dictionary: Can't completely remove entry


I have a Swift dictionary and I am trying to completely remove an entry. My code is as follows:

import UIKit

var questions: [[String:Any]] = [
    [
        "question": "What is the capital of Alabama?",
        "answer": "Montgomery"
    ],
    [
        "question": "What is the capital of Alaska?",
        "answer": "Juneau"
    ]
 ]

var ask1 = questions[0]
var ask2 = ask1["question"]

print(ask2!) // What is the capital of Alabama?

questions[0].removeAll()

ask1 = questions[0] // [:]
ask2 = ask1["question"] // nil - Should be "What is the capital of Alaska?"

I used questions[0].removeAll() to remove the entry but it leaves an empty entry. How can I completely remove an entry so that there is no trace?


Solution

  • There is nothing wrong with this behaviour, you are telling to the compiler that removes all the elements in a Dictionary and it's working fine:

    questions[0].removeAll()
    

    But you're declaring an Array<Dictionary<String, Any>> or in shorthand syntax [[String: Any]] and you need to remove the entry from your array too if you want to remove the Dictionary, see the following code:

    var questions: [[String: Any]] = [
       [
        "question": "What is the capital of Alabama?",
        "answer": "Montgomery"
       ],
       [
        "question": "What is the capital of Alaska?",
        "answer": "Juneau"
       ]
    ]
    
    var ask1 = questions[0]
    var ask2 = ask1["question"]
    
    print(ask2!) // What is the capital of Alabama?
    
    questions[0].removeAll()
    
    questions.removeAtIndex(0) // removes the entry from the array in position 0
    
    ask1 = questions[0] // ["answer": "Juneau", "question": "What is the capital of Alaska?"]
    ask2 = ask1["question"] // "What is the capital of Alaska?"
    

    I hope this help you.