var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
// 2. UPADTE KEY VALUE DICTIONARY
var oldVal = someDict.updateValue("Divakar", forKey : 1)
var someVar1 = someDict[1]
print( "Old value of key = 1 is \(oldVal)" )
print( "Value of key = 1 is \(someVar1)" )
print( "Value of key = 2 is \(someDict[2])" )
// 3. MODIFY THE EXISTING ELEMENT OF DICTIONARY
var oldVal2 = someDict[1]
someDict[1] = "New value of one"
var someVar2 = someDict[1]
print( "Old value of key = 1 is \(oldVal2)" )
print( "Value of key = 1 is \(someVar2)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
// 4. remove a key-value pair from a dictionary.
var removedValue = someDict.removeValue(forKey :2)
print( "Value of key = 1 is \(someDict[1])" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
// 5. ITERATE
for (key, value) in someDict {
print("Dictionary key \(key) - Dictionary value \(value)")
}
// 6. separate arrays for both keys and values
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)
print("Print Dictionary Keys")
for (key) in dictKeys {
print("\(key)")
}
print("Print Dictionary Values")
for (value) in dictValues {
print("\(value)")
}
//7. COUNT
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
print("Total items in someDict1 = \(someDict1.count)")
print("Total items in someDict2 = \(someDict2.count)")
// 8. isEmpty
var someDict3:[Int:String] = [Int:String]()
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")
-----------------------------------------------------
9. Passing dictionary from one function to another and get data
CODE </ >
var globalDict = [String:Int]()
func first(){
let stringsAsInts: [String:Int] = [
"zero" : 0,
"one" : 1,
"two" : 2,
"three" : 3,
"four" : 4,
"five" : 5,
"six" : 6,
"seven" : 7,
"eight" : 8,
"nine" : 9
]
globalDict = stringsAsInts
}
func second(){
first()
// print(globalDict)
let zero: Any! = globalDict["zero"] // Optional(0)
print(zero)
let one: Int! = globalDict["one"] // Optional(0)
print(one)
let two: Int! = globalDict["two"] // Optional(0)
print(two)
let nine: Int! = globalDict["nine"] // Optional(0)
print(nine)
}
second()
No comments:
Post a Comment