Jan
Jan

Reputation: 16114

Extract values of dictionary

struct Country {
  var translations : [String:String?]? // must be defined as optionals!
}

// example entry
translationsDict = [
   "translations": [
      "de":"Deutschland", 
      "en": "germany",
      "it": nil
   ]
]

How can I extract the values "Deutschland" and "germany" into a new array? result should be:

 ["germany", "Deutschland"]

Upvotes: 1

Views: 81

Answers (1)

Lawliet
Lawliet

Reputation: 3499

Firstly, get a collection of all values of translations, then convert it to an array.

if let collection = translationsDict["translations"]?.values {
    let array = Array(collection)
    print(array)
}

or

if let array = translationsDict["translations"]?.map({ $0.1 }) {
    print(array)
}

Upvotes: 1

Related Questions