JoshParadroid JoshParadroid - 1 year ago 90
Swift Question

How to a convert a Dictionary Slice to a Dictionary in Swift

I'm trying to convert

to a new dictionary missing one key (I don't care which one).
returns a Slice. I want a new Dictionary of the same type as

You can convert an Array slice to an array like this
let array = Array(slice)
. What's the equivalent for a Dictionary? If I try Dictionary(slice) I get the compilation error
Argument labels '(_:)' do not match any available overloads

Many thanks in advance.

Answer Source

There's no such thing as a DictionarySlice like there is ArraySlice. Instead, dropFirst() returns a Slice<Dictionary> which doesn't support key subscripting like Dictionary does. However, you can loop through a Slice<Dictionary> with key-value pairs just like you can with Dictionary:

let dictionary = ["a": 1, "b": 2, "c": 3]

var smallerDictionary: [String: Int] = [:]

for (key, value) in dictionary.dropFirst() {
    smallerDictionary[key] = value

print(smallerDictionary) // ["a": 1, "c": 3]

An extension would make this a bit more elegant:

extension Dictionary {

    init(_ slice: Slice<Dictionary>) {
        self = [:]

        for (key, value) in slice {
            self[key] = value


let dictionary = ["a": 1, "b": 2, "c": 3]
let smallerDictionary = Dictionary(dictionary.dropFirst())
print(smallerDictionary) // ["a": 1, "c": 3]

I wouldn't really recommend doing this, though, because

  • you don't know which key-value pair will be dropped, and
  • it's not truly random either.

But if you really want to do this, now you know how to do it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download