swift dictionary code example

Example 1: how to get key for dictionary in swift

var array_has_dictionary = [ // Start of array

   // Dictionary 1

   [ 
     "name" : "xxxx",
     "age" : "xxxx",
     "last_name":"xxx"
   ],

   // Dictionary 2

   [ 
     "name" : "yyy",
     "age" : "yyy",
     "last_name":"yyy"
   ],

 ] // end of array


cell.textLabel?.text =  Array(array_has_dictionary[1])[1].key
// Output: age -> yyy

Example 2: create dictionary swift

var someDict:[String:Int] = ["One":1, "Two":2, "Three":3] // creates dictionary
var someVar = someDict["One"] // accesses the value of key "One"

print("The value of key = One is \(someVar)")

Example 3: dictionary in swift

var someDict = [KeyType: ValueType]()

Example 4: how to get list of value from specific keys in array object in swift

import Foundation

let strings = [
    "one",
    "two",
    "three"
]

let ints = strings.map { (string) -> Int in
    return string.count
}