Eric Yu Eric Yu - 5 months ago 16
Swift Question

how do I remove one single element from an array dictionary?

dict = ["H": ["hello", "hi"], "J": ["joker"]]


how do i delete "hi" from so dict it will look like

dict = ["H": ["hello"], "J": ["joker"]]


do i use ? dict.removeAtIndex(), if so how ?

Answer

You can use indexOf as follow:

var dict = ["H": ["hello", "hi"], "J": ["joker"]]


if let index = dict["H"]?.indexOf("hi") {
    dict["H"]?.removeAtIndex(index)
}

dict // ["H": ["hello"], "J": ["joker"]]

Xcode 8 beta • Swift 3 would be:

var dict = ["H": ["hello", "hi"], "J": ["joker"]]


if let index = dict["H"]?.index(of: "hi") {
    dict["H"]?.remove(at: index)
}

dict
Comments