Robert Brusa
Robert Brusa

Reputation: 322

Converting mydict.keys into an array

I have a dictionary of type [String:String] and want to ask all keys into an array of Strings.

ortdict = [
    "aaa": "eins",
    "bbb": "zwei",
    "ccc": "drei"
]
let mykeys = ortdict.keys
print("\nkeys:", mykeys)

The printout then is:

keys: LazyMapCollection<Dictionary<String, String>, String>(_base: ["aaa": "eins", "bbb": "zwei", "ccc": "drei"], _transform: (Function))

That's not what I want, but I can not find a method that produces an array of my keys. Do I have to program this method myself (as swift-replacement for the previous allkeys-method for a NSDictionary)?

Upvotes: 1

Views: 234

Answers (2)

TekMi
TekMi

Reputation: 191

How about:

let keysArray = ortdict.keys.sort()

Upvotes: 1

Eric Aya
Eric Aya

Reputation: 70119

Use the Array initializer to transform the LazyMapCollection into an array:

let mykeys = Array(ortdict.keys)

print("\nkeys:", mykeys)

Prints:

keys: ["bbb", "aaa", "ccc"]

Note that a Swift Dictionary is an unordered collection. If you want the keys ordered, sort the resulting array instead of sorting the dictionary itself:

let mykeys = Array(ortdict.keys).sort()

Result:

keys: ["aaa", "bbb", "ccc"]

Upvotes: 0

Related Questions