How to assign string to NSDictionary using for loop? - ios

So, I retrieve song info using mpmediapicker on my application. I want to assign song info to dictionary so it's easy to populate it to tableview. But I found trouble when assigning value to dictionary on for loop.
Here is my code:
for thisItem in mediaItemCollection!.items as! [MPMediaItem]{
let itemUrl = thisItem.valueForProperty(MPMediaItemPropertyAssetURL)
as? NSURL
let itemTitle =
thisItem.valueForProperty(MPMediaItemPropertyTitle)
as? String
let itemArtist =
thisItem.valueForProperty(MPMediaItemPropertyArtist)
as? String
let itemArtwork =
thisItem.valueForProperty(MPMediaItemPropertyArtwork)
as? MPMediaItemArtwork
playlist = ["title" : itemTitle! , "artist" : itemArtist!, "song_url" : itemUrl!]
}
and below is what I got:
Optional({
artist = "ASKING ALEXANDRIA";
"song_url" = "ipod-library://item/item.mp3?id=5357233978197423496";
title = Alerion;
})
it's only retrieving the last song. How can I fix this problem ?
the format I want is like below:
Optional({artist = "ASKING ALEXANDRIA";"song_url" = "ipod-library://item/item.mp3?id=5357233978197423496";title = Alerion;}, {artist = "ASKING ALEXANDRIA";"song_url" = "ipod-library://item/item.mp3?id=5357239348197423496"; title = The Prophecy;}, {artist = "ASKING ALEXANDRIA";"song_url" = "ipod-library://item/item.mp3?id=53572339781974234123";title = Breathless;})
How can I do that?

If I am not wrong playlist is a NSDictionary
You have to create an NSMutableArray
var playlistArray : NSMutableArray = []
Now add the playlist in to array inside for loop.
playlistArray.addObject(playlist)
Print after completing the loop
println("\(playlistArray)")

You are not appending new data to the array you are just making the array equals the values
Try this:
playlist += ["title" : itemTitle! , "artist" : itemArtist!, "song_url" : itemUrl!]
or
playlist.append(["title" : itemTitle! , "artist" : itemArtist!, "song_url" : itemUrl!])
Assuming your playlist is an array of dictionaries that can be created like:
var playlist : [Dictionary<String, Int>] = []
or
var playlist = [Dictionary<String, Int>]()
or
var playlist : [[String:Int]] = []
or
var playlist = [[String:Int]]()

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 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)

One to many relations Parse

I've looked all over but I can't find an answer to this question.
I am saving a Podcasts and its related episodes to Parse but the following code only saves 1 episode and the podcast (I suppose every entry found in the for loop resets currentP and only the last value found gets saved).
let currentP = PFObject(className: self.podcastClass)
currentP["user"] = PFUser.currentUser()
currentP["name"] = name
currentP["artist"] = artist
currentP["summary"] = summary
currentP["feedURL"] = feedURL
currentP["artworkURL"] = artworkURL
currentP["artwork"] = artwork
currentP["date"] = date
let episodesToParse = PFObject(className: self.episodesClass)
for episode in episodes {
episodesToParse["showDate"] = episode.date
episodesToParse["title"] = episode.title
episodesToParse["downloadURL"] = episode.enclosures[0].valueForKey("url") as? String
episodesToParse["showNotes"] = episode.summary
episodesToParse["localPath"] = ""
episodesToParse["isDownloaded"] = "no"
episodesToParse["parent"] = currentP
}
episodesToParse.saveInBackground()
If I use something like episodesToParse.addObject(episode.date, forKey: "showDate") then the following error is returned:
[Error]: invalid type for key showDate, expected date, but got array (Code: 111, Version: 1.8.1)
I'm not sure how to proceed. What I want is currentP to be saved as it is and all its episodes to be saved in a different class with a relationship to its parent (Podcast). I found tons of ways to do this if you're adding one episode at a time but not a whole bunch of them (I would like to be able to save 500 instance of episodesToParseat once.
Thanks for your help.
Your problem is, that you save the episodesToParse after the loop. You have to move the episodesToParse.saveInBackground() inside the loop so that everytime the loop sets the properties of the episode the episode gets updated:
for episode in episodes {
episodesToParse["showDate"] = episode.date
episodesToParse["title"] = episode.title
episodesToParse["downloadURL"] = episode.enclosures[0].valueForKey("url") as? String
episodesToParse["showNotes"] = episode.summary
episodesToParse["localPath"] = ""
episodesToParse["isDownloaded"] = "no"
episodesToParse["parent"] = currentP
//Inside
episodesToParse.saveInBackground()
}
Or you could use PFObject.saveAllInBackground to save all objects:
var episodesToSave[PFObject] = []
for episode in episodes {
var episodeToParse
episodeToParse["showDate"] = episode.date
episodeToParse["title"] = episode.title
episodeToParse["downloadURL"] = episode.enclosures[0].valueForKey("url") as? String
episodeToParse["showNotes"] = episode.summary
episodeToParse["localPath"] = ""
episodeToParse["isDownloaded"] = "no"
episodeToParse["parent"] = currentP
//Add to episode-array
episodesToSave.append(episodesToParse)
}
//Save all objects in the array
PFObject.saveAllInBackground(episodesToSave)

Convert String Array to JSON or 2D Array SWIFT

I currently have a NSMutableArray "localArray" and I am trying to create that into a JSON Array or a 2D Array. I get this data my creating a database and running a query using a for loop on the database.
{
Food,
Burger,
3.99,
1.25,
POP,
Crush,
1.99,
.89,
and more.
}
The reason why I am looking for a JSON or 2d Array is I want to hold the data in the localArray in such a way that I can identify by type and then do something like .valueForKey("Name") or .valurForKey("Price") and add that to my tableview's cell text label or labels.
{
{
Type Food,
Name Burger,
Price 3.99,
Cost 1.25,
},
{
Type POP,
Name Crush,
Price 1.99,
Cost .89,
},
and more
}
I have already tried JSONSerialization, but that failed and also tried 2d Array but no luck.
Any help will be highly appreciated.
This is how I Query and add the data to localArray
let queryType = data.select(ada, code, name, proof, size, case_size, price)
.filter(bevType == type)
let rows = Array(queryType)
for row in rows{
let name = row[self.name]
let type = row[self.type]
let cost = row[self.cost]
let price = row[self.price]
localArray.addObject(name)
localArray.addObject(type)
localArray.addObject(cost)
localArray.addObject(price)
}
I solved it myself by creating a dictionary.
for row in rows{
var rDict: Dictionary = [String: String]()
rDict["Name"] = row[self.name]
rDict["Type"] = row[self.type]
rDict["Cost"] = row[self.cost]
rDict["Price"] = row[self.price]
localArray.addObject(rDict)
}
If fields are always repeating in count of 4, you can try doing this:
var array = [[String: AnyObject]]()
for var i = 0 ; i < array.count ; i += 4 {
var k = 0
var dict = [String: AnyObject]
dict["Type"] = array[i + k++]
dict["Name"] = array[i + k++]
dict["Price"] = array[i + k++]
dict["Cost"] = array[i + k]
array.append(dict)
}
Then extract dictionary from this swift array and use same keys to extract data from dictionary to be used in your cell like
let dict = array[indexPath.row]
cell.title = dict["Name"]

How to append associative array elements in Swift

How do I create and append to an associative array in Swift? I would think it should be something like the following (note that some values are strings and others are numbers):
var myArray = []
var make = "chevy"
var year = 2008
var color = "red"
myArray.append("trackMake":make,"trackYear":year,"trackColor":color)
The goal is to be able to have an array full of results where I can make a call such as:
println(myArray[0]["trackMake"]) //and get chevy
println(myArray[0]["trackColor"]) //and get red
Simply like this:
myArray.append(["trackMake":make,"trackYear":year,"trackColor":color])
Add the brackets. This will make it a hash and append that to the array.
In such cases make (extensive) use of let:
let dict = ["trackMake":make,"trackYear":year,"trackColor":color]
myArray.append(dict)
The above assumes that your myArray has been declared as
var myArray = [[String:AnyObject]]()
so the compiler knows that it will take dictionary elements.
I accept above answer.It is good.Even you have given correct answer,I like to give simplest way.The following steps are useful,if you guys follow that.Also if someone new in swift and if they go through this,they can easily understand the steps.
STEP 1 : Declare and initialize the variables
var array = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()
var make = "chevy"
var year = 2008
var color = "red"
STEP 2 : Set the Dictionary(adding keys and Values)
dict["trackMake"] = make
dict["trackYear"] = year
dict["trackColor"] = color
println("the dict is-\(dict)")
STEP 3 : Append the Dictionary to Array
array.append(dict)
println("the array is-\(array)")
STEP 4 : Get Array values to variable(create the variable for getting value)
let getMakeValue = array[0]["trackMake"]
let getYearValue = array[0]["trackYear"]
let getColorValue = array[0]["trackColor"]
println("the getMakeValue is - \(getMakeValue)")
println("the getYearValue is - \(getYearValue)")
println("the getColorVlaue is - \(getColorValue)")
STEP 5: If you want to get values to string, do the following steps
var stringMakeValue:String = getMakeValue as String
var stringYearValue:String = ("\(getYearValue as Int)")
var stringColorValue:String = getColorValue as String
println("the stringMakeValue is - \(stringMakeValue)")
println("the stringYearValue is - \(stringYearValue)")
println("the stringColorValue is - \(stringColorValue)")
STEP 6 : Finally the total output values are
the dict is-[trackMake: chevy, trackColor: red, trackYear: 2008]
the array is-[{
trackColor = red;
trackMake = chevy;
trackYear = 2008;
}]
the getMakeValue is - Optional(chevy)
the getYearValue is - Optional(2008)
the getColorVlaue is - Optional(red)
the stringMakeValue is - chevy
the stringYearValue is - 2008
the stringColorValue is - red
Thank You
This sounds like you are wanting an array of objects that represent vehicles. You can either have an array of dictionaries or an array of vehicle objects.
Likely you will want to go with an object as Swift arrays and dictionaries must be typed. So your dictionary with string keys to values of differing types would end up having the type [String : Any] and you would be stuck casting back and forth. This would make your array of type [[String : Any ]].
Using an object you would just have an array of that type. Say your vehicle object's type is named Vehicle, that would make your array of type [Vehicle] and each array access would return an instance of that type.
If I want to try it with my own statement. Which also I want to extend my array with the data in my dictionary and print just the key from dictionary:
var myArray = ["Abdurrahman","Yomna"]
var myDic: [String: Any] = [
"ahmed": 23,
"amal": 33,
"fahdad": 88]
for index in 1...3 {
let dict: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = myDic[myArray] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(myArray)
// replace back into `data`
myDic[myArray] = existingItems
}

Resources