How to Insert values in Dictionary in swift - swift

I first declare dictionary
let storeSentenceOrdering = [String, Int ]();
then I want to insert value in it but I am getting an error:

- We can do this in following way
var carDictionary: [String:Int] = [:]
// Below is a subscript way of adding or updating value to the Dictionary, if the key is not present then the key is inserted with the assigned value else its updated with the new value
carDictionary["Ford"] = 345000
carDictionary["Hyundai"] = 546788
print(carDictionary)
- We can also use update to add value to the existing Dictionary
carDictionary.updateValue(234500,forKey:("Wolkswagen"))
- Dictionary can be initialized in one the following ways
var carDictionaryOne: [String:Int] = [:]
var carDictionaryTwo: [String:Int] = ()
var carDictionaryThree = ["Ford":12345, "Audi":57689]

try it...
var dict : NSDictionary!
dict = [1:"Hello", 2:"How", 3:"Are", 4:"You"]
let value = dict[1]
print(value!) // Print First Element
//print all element
for(var i=1; i<5; i++)
{
let value = dict[i]
print(value)
}

Related

Getting Array value in a dictionary swift

I am trying to get key and value in a Dictionary while I am able to the key and map it to a dictionary, I am unable to get the value which is an array.
var dict = [String: [String]]
I was able to get the key as an array which is what I want like:
var keyArray = self.dict.map { $0.key }
How can I get the value which is already an array
Use flatMap if you want to flatten the result you get when you use map which is of type [[String]].
let valueArray = dict.flatMap { $0.value } // gives `[String]` mapping all the values
Here is how you get each string count Array
var dict = [String: [String]]()
let countOfEachString = dict.map { $0.value }.map{ $0.count }
Each value is a string array .. so to access each array you need to use map again

Swift dictionary, a key with multiple values

I would like to know how I can make a key of a dictionary have multiple values according to the data that comes to it.
Attached basic example:
var temp = [String: String] ()
temp ["dinningRoom"] = "Table"
temp ["dinningRoom"] = "Chair"
In this case, I always return "Chair", the last one I add, and I need to return all the items that I am adding on the same key.
In this case, the "dinningRoom" key should have two items that are "Table" and "Chair".
You can use Swift Tuples for such scenarios.
//Define you tuple with some name and attribute type
typealias MutipleValue = (firstObject: String, secondObject: String)
var dictionary = [String: MutipleValue]()
dictionary["diningRoom"] = MutipleValue(firstObject: "Chair", secondObject: "Table")
var value = dictionary["diningRoom"]
value?.firstObject
You can declare a dictionary whose value is an array and this can contain the data you want, for example:
var temp = [String: [String]]()
temp["dinningRoom"] = ["Table", "Chair", "Bottle"]
If you want to add a new element you can do it this way:
if temp["dinningRoom"] != nil {
temp["dinningRoom"]!.append("Flower")
} else {
temp["dinningRoom"] = ["Flower"]
}
Now temp["dinningRoom"] contains ["Table", "Chair", "Bottle", "Flower"]
Use Dictionary like this:
var temp = [String: Any]()
temp["dinningRoom"] = ["Table", "Chair"]
If you want to fetch all the elements from dinningRoom. You can use this:
let dinningRoomArray = temp["dinningRoom"] as? [String]
for room in dinningRoomArray{
print(room)
}
It is not compiled code but I mean to say that we can use Any as value instead of String or array of String. When you cast it from Any to [String]
using as? the app can handle the nil value.

Swift3 loop dictionary to add value

I m new to programming I just playing around in playground, I am trying to loop in a dictionary to do some calculation and add them into new dictionary however, I can only add one dictionary value back. I am not sure why. Can anymore tell me and point out the point?
var name:String?
var popDict: [String: Array<Double>]?
var FinalDict: [String: Array<Double>]?
var mean: Double?
var elementSideArr: Array<Double>?
var nameArray = ["Olivia": [1,2,2,2,1,2,1,0.0001,0,1,2], "Amber": [52,52,65,66,57,63,62,0.0001,0,0,0]]
var doubleArr = [Double]()
for (key, value) in nameArray{
let thisValue = value
let arrayS = thisValue.prefix(7)
let slice = arrayS[0...6]
let popSideArr = Array(slice)
let average: Double = (popSideArr as NSArray).value(forKeyPath: "#avg.self") as! Double
mean = average
let thatValue = value
let arraySS = thatValue.suffix(3)
let sslice = arraySS[8...10]
elementSideArr = Array(sslice)
elementSideArr?.insert(average, at: 0)
let dict = ["\(key)": elementSideArr!]
for (key,value) in dict{
popDict = dict
}
}
print(popDict!)
["Olivia": [1.5714285714285714, 0.0, 1.0, 2.0]] // It is the only output but it should be 2 items.
Problem is in your inner for loop you are initializing whole new dictionary to popDict also you don't need for loop if you are having single key and value pair with your dictionary.
Replace line of codes:
let dict = ["\(key)": elementSideArr!]
for (key,value) in dict{
popDict = dict
}
With:
popDict["\(key)"] = elementSideArr!
Note: No need to cast swift array to NSArray to calculate average you can simply use reduce to get total and then divide the total with array count.
let array = popSideArr as? [Int] ?? []
let res = Double(array.reduce(0, +)) / Double(popSideArr.count)

accessing inner dictionaries (dictionary of dictionaries) with one entry, when not knowing what key or value for that entry are

This is how I declared my dictionary:
var dataDictionary: [NSIndexPath:[Int:Bool]]!
The inner dictionary will always have just one entry e.g. [1:true]. When I search dataDictionary I specify a NSIndexPath. The inner dictionary gets returned. Sth like this:
var innerDictionary = dataDictionary[indexPath] // is of type [Int:Bool]
I would like to access inner dictionarys key and value, but I don't want to specify an Integer or Bool, because it is unknown. I only want to get that Int and/or Bool value stored in inner dictionary. No search of inner dictionary is needed, because if will always contains just one entry. Maybe something like this:
var key = innerDictionary.key
var value = innerDictionary.value
How can this be accomplished?
If your dictionary has only one entry, and you don't know the key, with Swift 2 you can get the first element of the keys sequence safely with if let:
let innerDictionary = [42: true]
if let k = innerDictionary.keys.first {
print(k) // prints 42
} else {
// dict is empty
}
Same for the value:
if let v = innerDictionary.values.first {
print(v) // prints true
} else {
// key has no value
}
Try by this way:
func nestedDic(){
var innerDictionary:NSDictionary = ["Item 1": "data 0", "Item 2": "data 1"]
//NSLog("original object:\(innerDictionary)")
NSLog("all keys array:\(innerDictionary.allKeys)")
if(innerDictionary.isKindOfClass(NSDictionary)){
for key in innerDictionary.allKeys{
let value = innerDictionary.valueForKey(key as! NSString as String)
NSLog("key value = \(value as! String)")
}
}
}
You could create a simple struct for the inner dictionary if there is only one entry, then you are able to use your favorite property names.
struct InnerDictionary {
var key = 0
var value = false
}
let indexPath = NSIndexPath(index: 1)
var dataDictionary = [indexPath: InnerDictionary(key: 1, value: true)]
if let innerDictionary = dataDictionary[indexPath] {
var key = innerDictionary.key
var value = innerDictionary.value
}

'AnyObject?' does not have a member named 'count'

I'm trying to loop through an (as I would interpret) array by arrayname.count like:
if var storedToDoItems: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") {
toDoItems = []
for var i = 0; storedToDoItems.count; i++ {
toDoItems.append(storedToDoItems[i] as NSString)
}
}
and receive the error in the title marked by storedToDoItems.count. I'm populating first storedToDoItems like this:
...
toDoItems.append(tb_toDoItem.text)
let fixedToDoItems = toDoItems
// Store items
NSUserDefaults.standardUserDefaults().setObject(fixedToDoItems, forKey: "toDoItems")
// Save the stored stuff
NSUserDefaults.standardUserDefaults().synchronize()
...
If you store an array to the user defaults, you should try to cast it to an array when you extract it.
If toDoItems is defined as an array of strings [String], then you just have to use optional binding combined with optional cast, and just copy the extracted array to toDoItems:
if let storedToDoItems: [String] = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = storedToDoItems
}
Being an array a struct, i.e. a value type, it is assigned by copy, so when assign storedToDoItems to toDoItems, a copy of it is created and assigned - so you don't need to manually add each element individually.
Your code instead has 2 errors:
you have defined storedToDoItems as an optional AnyObject, and optionals don't have a count property.
even if it is not defined as optional, AnyObject doesn't have a count property as well. It's irrelevant that the actual type stored in the variable is an array, the variable is declared as AnyObject and that is how is treated by the compiler.
You need to tell what's inside:
toDoItems = [String]()
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
for item in storedToDoItems {
toDoItems.append(item)
}
}
and even shorter:
toDoItems = [String]()
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = storedToDoItems
}
I just used this Bold line will work for you hopefully
if var toDoStored: [String] = NSUserDefaults.standardUserDefaults().objectForKey("toDoSaved") as? [String]{
tblItems = []
for var i = 0; i < toDoStored.count ; ++i {
tblItems.append(toDoStored[i] as NSString)
}
}