0

Given the dictionary:

let dictionary = [ "one": 1, "two": 2, "three": 3]

I want to create a new version with one of the items removed based on its key. So I'm trying to use...

let dictionaryWithTwoRemoved = dictionary.filter { $0.0 != "two" }

... which achieves what I want HOWEVER the two dictionaries have differing types...

`dictionary` is a `[String: Int]`
`dictionaryWithTwoRemoved` is a `[(key: String, value: Int)]`

Which is consequently making my life difficult.

If I try to cast like so...

let dictionaryWithThreeRemoved = dictionary.filter { $0.0 != "three" } as! [String: Int]

...I get the following WARNING...

Cast from '[(key: String, value: Int)]' to unrelated type '[String : Int]' always fails

and the code also crashes with EXC_BAD_INSTRUCTION at runtime.

Help!

2
  • 1
    Dictionary does not have a filter function (yet). You are using the filter from Sequence but Dictionary is a sequence of key-value pairs. After calling filter, it's not a dictionary any more, it's a list of key-value pairs. Commented Apr 5, 2017 at 19:45
  • Compare stackoverflow.com/questions/32604897/swift-filter-dictionary. Commented Apr 5, 2017 at 19:46

2 Answers 2

1

If you want an extension method to help you remove the values here you go...

extension Dictionary {
    func removingValue(forKey key: Key) -> [Key: Value] {
        var mutableDictionary = self
        mutableDictionary.removeValue(forKey: key)
        return mutableDictionary
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use reduce to do this.

//: Playground - noun: a place where people can play

import Cocoa

let dictionary = [ "one": 1, "two": 2, "three": 3]
let newDictionary = dictionary.reduce([:]) { result, element -> [String: Int] in
    guard element.key != "two" else {
        return result
    }

    var newResult = result
    newResult[element.key] = element.value
    return newResult
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.