Range For Keys and Values Of Dictionary

I came across a code

let myFruitBasket = ["apple":"red", "banana": "yellow", "budbeeri": "dark voilet", "chikoo": "brown"]

Can we have range for keys and values of dictionary, it will be convenient

for keys

print(myFruitBasket.keys[1...3])

// banana, budbeeri, chikoo

same for values

print(myFruitsBasket.values[1...3])

// yellow, voilet, brown

Answered by DTS Engineer in 848555022

It would help if you posted more details about what you plan to do with these ranges. However, what you’re asking for is supported, because the values returned by both keys and values conforms to Collection. So, for example, you can do this:

let myFruitBasket = ["apple":"red", "banana": "yellow", "budbeeri": "dark voilet", "chikoo": "brown"]
print(myFruitBasket.keys.dropFirst())

This doesn’t print a nice value but you can solve that by converting to an array:

print(Array(myFruitBasket.keys.dropFirst()))
// ["chikoo", "apple", "banana"]

IMPORTANT The keys and values collection doesn’t guarantee the order, which is why this doesn’t print the value you’re expecting.

And that means that dropping the first element only makes sense in some cases. And hence my earlier request for more details about what you’re planning to do with these ranges.

ps You might want to ask questions like this over in Swift Forums > Using Swift. I’m happy to answer them here, but there’s a wider audience of Swift aficionados over there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

It would help if you posted more details about what you plan to do with these ranges. However, what you’re asking for is supported, because the values returned by both keys and values conforms to Collection. So, for example, you can do this:

let myFruitBasket = ["apple":"red", "banana": "yellow", "budbeeri": "dark voilet", "chikoo": "brown"]
print(myFruitBasket.keys.dropFirst())

This doesn’t print a nice value but you can solve that by converting to an array:

print(Array(myFruitBasket.keys.dropFirst()))
// ["chikoo", "apple", "banana"]

IMPORTANT The keys and values collection doesn’t guarantee the order, which is why this doesn’t print the value you’re expecting.

And that means that dropping the first element only makes sense in some cases. And hence my earlier request for more details about what you’re planning to do with these ranges.

ps You might want to ask questions like this over in Swift Forums > Using Swift. I’m happy to answer them here, but there’s a wider audience of Swift aficionados over there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Range For Keys and Values Of Dictionary
 
 
Q