Getting information from a NSDictionary - ios

I named the result resultdict and the NSDictionary looks like this:
{
data = (
);
summary = {
"total_count" = 514;
};
}
How do I get the "514" from that? I am using swift.

Try this one
var totalCount = yourDict.valueForKeyPath("summary.total_count")

You can just do it like :
var totalCount = yourDict.objectForKey("summary").objectForKey("total_count")
convert it to string
var totalCount = yourDict.objectForKey("summary").objectForKey("total_count") as! String
If you use :
println(totalCount)
will result in
Optional(514)
Use that variable as you want

Related

create a dictonary with for loop in swift

I just want to create a dictionary with the help of for loop
sample code :
var counter: Int = 1;
var pageCountDict = [String:Any]();
for filterCount in counter..<6
{
if let count = "page_\(filterCount)_vtime" as? String
{
pageCountDict = [count: timeInterval_Int];
}
}
print(pageCountDict);
This print command give me only last value of forloop
I just want all the value of this variable pageCountDict in a dictonary
The way to assign to a dictionary is first use the subscript and assign the value to it:
pageCountDict[YourKey] = YourValue
Also, you can see many examples and explanations in Apple documentation regarding dictionaries.
With each loop, you are replacing the dictionary with one that contains only one element. What you want to do is this :
pageCountDict[count] = timeInterval_Int
Also, you shouldn't need the as? String part. This should be sufficient :
for filterCount in counter..<6
{
pageCountDict[count] = "page_\(filterCount)_vtime"
}
var pageCountDict = [String:Any]()
You can add values to this dictionary by merging previous contents and new data as follows...
let counter: Int = 1
var pageCountDict = [String:Any]()
for filterCount in counter..<6
{
let value = 9
let count = "page_\(filterCount)_vtime" //'if' is not needed as it is always true
pageCountDict.merge([count: timeInterval_Int], uniquingKeysWith:{ (key, value) -> Any in
//assign value for similar key
timeInterval_Int
})
}
print(pageCountDict)`

How to declare an empty array of type 'CNLabeledValue' using Swift 3?

The code that used to work in iOS 9 was:
var valuesArray : [CNLabeledValue] = []
But I can't figure out how to do it in Swift 3.
This is the solution:
var phoneNumbers : [CNLabeledValue<CNPhoneNumber>] = []
As OOPer pointed out in this post:
CNLabeledValue's generic parameter is declared as <ValueType : NSCopying, NSSecureCoding>. So, in this case, you can choose any type which conforms to NSCopying and NSSecureCoding. NSString does and String does not.
something like this (with example to fill out phone number):
let phonesArray : [Phones] = phones!
var phonesToAdd = [CNLabeledValue]()
for phone in phonesArray
{
if let phoneT = phone.phoneType
{
if phoneT.lowercaseString == "mobile"
{
let mobilePhone = CNLabeledValue(label: "mobile",value: CNPhoneNumber(stringValue: phone.phone))
phonesToAdd.append(mobilePhone)
}
if phoneT.lowercaseString == "landline"
{
let landlinePhone = CNLabeledValue(label: "landline",value: CNPhoneNumber(stringValue: phone.phone))
phonesToAdd.append(landlinePhone)
}
}
}
contactData.phoneNumbers = phonesToAdd

How do I create a dictionary from an array of objects in swift 2.1?

I have an array of type "drugList", and they are derived from a struct "DrugsLibrary":
struct DrugsLibrary {
var drugName = ""
var drugCategory = ""
var drugSubCategory = ""
}
var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["": [""," "]]
My data model is initialized using this function:
func createDrugsList() {
var drug1 = DrugsLibrary()
drug1.drugName = "drug1"
drug1.drugCategory = "Antibiotics"
drug1.drugSubCategory = "Penicillins"
self.drugList.append(drug1)
var drug2 = DrugsLibrary()
drug2.drugName = "drug2"
drug2.drugCategory = "Antibiotics"
drug2.drugSubCategory = "Penicillins"
self.drugList.append(drug2)
var drug3 = DrugsLibrary()
drug3.drugName = "drug2"
drug3.drugCategory = "Antibiotics"
drug3.drugSubCategory = "Macrolides"
self.drugList.append(drug3)
}
my problem is that i'm trying to create a dictionary from the drugList where the key is the drugSubCategory and the value is the drug name. The value should be an array if there are several drugs in this subcategory
for example, the dictionary should look something like this for this example:
dictionary = [
"Penicillins": ["drug1","drug2"]
"Macrolides": ["drug3"]
]
I tried this method:
for item in drugList {
dictionary["\(item.drugSubCategory)"] = ["\(item.drugName)"]
}
this gave a dictionary like this, and it couldn't append drug2 to "Penicllins":
dictionary = [
"Penicillins": ["drug1"]
"Macrolides": ["drug3"]
]
So I tried to append the items into the dictionary using this method but it didn't append anything because there were no common items with the key "" in the data model:
for item in drugList {
names1[item1.drugSubCategory]?.append(item1.drugName)
}
Anyone knows a way to append drug2 to the dictionary?
I would appreciate any help or suggestion in this matter.
You need to create a new array containing the contents of the previous array plus the new item or a new array plus the new item, and assign this to your dictionary:
for item in drugList {
dictionary[item.drugSubCategory] = dictionary[item.drugSubCategory] ?? [] + [item.drugName]
}
You can use .map and .filter and Set to your advantage here. First you want an array of dictionary keys, but no duplicates (so use a set)
let categories = Set(drugList.map{$0.drugSubCategory})
Then you want to iterate over the unique categories and find every drug in that category and extract its name:
for category in categories {
let filteredByCategory = drugList.filter {$0.drugSubCategory == category}
let extractDrugNames = filteredByCategory.map{$0.drugName}
dictionary[category] = extractDrugNames
}
Removing the for loop, if more Swifty-ness is desired, is left as an exercise to the reader ;).
I have two unrelated observations:
1) Not sure if you meant it as an example or not, but you've initialized dictionary with empty strings. You'll have to remove those in the future unless you want an empty strings entry. You're better off initializing an empty dictionary with the correct types:
var dictionary = [String:[String]]()
2) You don't need to use self. to access an instance variable. Your code is simple enough that it's very obvious what the scope of dictionary is (see this great writeup on self from a Programmers's stack exchange post.
Copy this in your Playground, might help you understand the Dictionaries better:
import UIKit
var str = "Hello, playground"
struct DrugsLibrary {
var drugName = ""
var drugCategory = ""
var drugSubCategory = ""
}
var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["":""]
func createDrugsList() {
var drug1 = DrugsLibrary()
drug1.drugName = "drug1"
drug1.drugCategory = "Antibiotics"
drug1.drugSubCategory = "Penicillins"
drugList.append(drug1)
var drug2 = DrugsLibrary()
drug2.drugName = "drug2"
drug2.drugCategory = "Antibiotics"
drug2.drugSubCategory = "Penicillins"
drugList.append(drug2)
var drug3 = DrugsLibrary()
drug3.drugName = "drug2"
drug3.drugCategory = "Antibiotics"
drug3.drugSubCategory = "Macrolides"
drugList.append(drug3)
}
createDrugsList()
print(drugList)
func addItemsToDict() {
for i in drugList {
dictionary["item \(i.drugSubCategory)"] = "\(i.drugName)"
}
}
addItemsToDict()
print(dictionary)

How can I get the value of dict for the set of values in an array in Swift 2.0?

I am not sure I framed the question correctly. But this is the explanation: I have a dictionary of contacts:
var arrOfDictContacts = NSMutableArray()
self.arrOfDictContacts.addObject(["\(names)":"\(numb)"])
After appending
arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
I have an array of names arrOfNames = ["Arun", "Chitra"]
Now I want the respective number of those names from dict in an array like this:
arrOfNumbers = ["+123", "+345"] // Expected Output
How can I fetch them?
You can do it like this:
var arrOfDictContacts = Dictionary<String, String>()
arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
var arrOfNames = ["Arun", "Chitra"]
var arrOfContacts = [String]()
for name in arrOfNames {
arrOfContacts.append(arrOfDictContacts[name]!)
}
println("\(arrOfContacts)")
Here you go...
let arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
let arrOfNames = ["Arun", "Chitra"]
var arrOfNumbers = [String]()
for name in arrOfNames {
if let aNumber = arrOfDictContacts[name] {
arrOfNumbers.append(aNumber);
}
}
This one is a one-liner:
arrOfNames.map({ arrOfDictContacts[$0] })
Please try this:
let dict = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
let names = ["Arun", "Babu"]
let allValues = dict.map({ $1 })
let valuesByName = names.map({ dict[$0] })
print("\(allValues)")
print("\(valuesByName)")
Here is how the output will look like in playground:
I think you'd better learn more about map, filter, ... in Swift. If the language provides the elegant way to do something, make sure that you utilize it instead of reinventing the wheel.

How to parse NSMutableDictionary in Swift programming?

In my apple watch interface controller "reply" object contains Json response in NSDictionary. Here is my response i need the "accountName" from this below response. How to parse it in Swift programming.
[Accounts: (
{
accountName = "ABCD";
idNumber = 114000093;
email = "xyz#gmail.com";
index = 0;
nickName = "Suites";
},
{
accountName = "EFGH";
idNumber = 114000094;
email = "abc#gmail.com";
index = 1;
nickName = "Sultan";
}
)]
I have tried like below:
WKInterfaceController.openParentApplication(["request" : "GetData"], reply: { (reply, error) -> Void in
println(reply)
self.accountNames = reply["Accounts"] as? NSMutableArray
println(self.accountNames)
This is very easy, you can try out by your own, and can google also, there are lots and lots of example available, you just need to brush up little bit.
Btw, You can try like this,
let accountArray : NSArray = reply.objectForKey("Accounts") as! NSArray
let accountDic : NSDictionary = accountArray.objectAtIndex(0) as! NSDictionary
let accountName : NSString = accountDic.valueForKey("accountName") as! NSString
Hope, this helps you.
Try this :
let accountInfos = (reply.valueForKey("Accounts") as [NSDictionary]).map {
YourModelClass(accountName: $0["accountName"] as String, idNumber: $0["idNumber"] as String ..... same for all other)
}
self.yourMutableArray.addObjectsFromArray(accountInfos)
let accountName = (yourMutableArray.objectAtIndex(0)as YourModelClass).accountName
println(accountName)
And your model class :
class YourModelClass : NSObject {
var accountName : String?
.
.
init(accountName:String, ......) {
self.accountName = accountName
}

Resources