I have a .plist in Swift. It is set up as follows
I have trouble finding information on how to read information from a .Plist.
I want to be able to randomly select one of the 845 Items in the EmojiList. Once I have that Item, then I want to have access to that Item's emoji string value and its description string value.
Programatically how would I go about accessing a random item inside the item list? And then having access to that specific item's properties?
First load the plist in to an array of dictionaries. Each dictionary represents one emoji. Then generate a random index of the array, and pull out the dictionary at that index. Now use the dictionary to access the properties of the emoji.
var emojiArray: NSArray?
if let path = NSBundle.mainBundle().pathForResource("name-of-file", ofType: "plist"){
emojiArray = NSArray(contentsOfFile: path)
}
if let array = emojiArray {
let randomIndex = arc4random_uniform(array.count) // random number from 0 to array.count - 1
let emojiDictionary = array[randomIndex]
println("emoji value: \(emojiDictionary["emoji"]), emoji description: \(emojiDictionary["description"])"
}
Related
I have a dictionary in which I'm adding values like so...
var mydictionary = ["id": "", "quantity": "","sellingPrice":""] as [String : Any]
dictionary["id"] = product?.id
dictionary["quantity"] = product?.quantity
dictionary["sellingPrice"] = product?.theRate
And these values I added to an array like so...
self.arrayOfDictionary.append(mydictionary)
But if arrayOfDictionary already contains mydictionary, I don't want to add it. Else, I want to add it.
The basic idea here is to add data from collection view items to array of dictionary. When I click on the buttons that I have on each collection view item the data on it is added to an array of dict. while at the same time showing those data in a tableviewcell. But when I navigate back from the tableview & visit the collectionview items again and click on some other collecn.view item, so as to add them to the array of dictionary as before, then the item that was added initially to the array of dictionary gets added again. This has to be somehow prevented.
As suggested by another SO user something like this was tried to prevent this duplication...
if self.arrayOfDictionary.contains(where: { (dict) -> Bool in
"\(dict["id"] ?? "")" != "\(dictionary["id"] ?? "")"}) {
self.arrayOfDictionary.append(dictionary)
}
But this doesn't seem to work. With this nothing is added to the array and its totally empty. Hope somebody can help...
Try this code to avoid duplication
I hope "id" value will be unique in your dictionary.
var mydictionary = ["id": "1", "quantity": "","sellingPrice":""] as [String : Any]
var arrayOfDictionary = [Dictionary<String, Any>]() //declare this globally
let arrValue = arrayOfDictionary.filter{ (($0["id"]!) as! String).range(of: mydictionary["id"]! as! String, options: [.diacriticInsensitive, .caseInsensitive]) != nil }
if arrValue.count == 0 {
arrayOfDictionary.append(mydictionary)
}
I've got better idea then every time you perform loop to check unique ness.
Maintain one Bool array of same size of your collectionView Items array with predefined false values each.
When you click on button of collection View item, change flag of Bool array with same index. And simultaneously you can disable the button also(if you want). Otherwise whenever user clicks on button, just check flag from Bool array and add Dictionary to new array as needed.
Here, your new array will be performed and you will same process and time of looping also.
One way to approach the problem could be to construct a structure which contains product details:
/// Details Of A Product
struct ProductDetails{
var id: String!
var quantity: Int!
var sellingPrice: Int!
}
Then create a dictionary which stores the product details with the key being the "ID" e.g:
var products = [String: ProductDetails]()
You could then create a product like so:
let productA = ProductDetails(id: "1", quantity: 100, sellingPrice: 10)
To add a unique product to your dictionary you could use a function like this:
/// Adds A Product To The Products Dictionary
///
/// - Parameter product: ProductDetails
func addProductDetails(_ product: ProductDetails){
//1. If A Product Exists Ignore It
if products[product.id] != nil{
print("Product With ID \(product.id!) Already Exists")
}else{
//2. It Doesn't Exist So Add It To The Dictionary
products[product.id] = product
}
}
I tested this quickly and it won't allow products which have duplicate ID's. although of course you could change the parameter as needed.
Trying to figure out how to display an array of dictionary data key,value returning form a server as a json on a uilabel or textfield.
Here is the dictionary
.
I want it to be displayed like this
I assume your JSON data is in this format:
let jsonColours = ["Colour": "Moss Green", "Fabric": "Cotton"...]
You can try running a for/in loop on the jsonColour:
for data in jsonColour {
let key = data.key //key value which is colour or fabric
let value = data.value //value which would be moss green or cotton
}
I´m searching for a way to save the data a user enters in two textfields in a tableview. The user has to enter the name and the height of person in a tableview and I want to save it to a custom array.
struct PersonData {
var name: String
var height: Int
init(name: String, height: Int) {
self.name = name
self.height = height
}
}
I´ve searched and i found this Swift: retrieving text from a UITextField in a custom UITableViewCell and putting it in an array but still got two questions.
How i add item to my custom array? I try it with this:
personData[textField.tag].name = textField.text!
Isn´t a easier way to do it?
Thank you!!
If I understood your question properly then heres a possible solution.
You initialise an array of type PersonData. Then you make an object of type PersonData. Whenever you have some info, you store it in this object and append the object to the array created.
let array = [PersonData]()
let personDataObject = PersonData()
//After you store the values in the object you add the object to you array.
personDataObject.name = textField1.text
personDataObject.height = textField2.text //You need to convert this to Int. Try personDataObject.height = textField2.text as? Int or personDataObject.height = Int(textField2.text)
array.append(personDataObject)
Most of the posts here are on about how to convert a set into an array.But I would like to know if I could convert an array to a set.I have downloaded my array from parse and want to convert it to a set because I want the user to edit their details and the form builder I used needs to accept a set data type only.
This is what I got.The "Subjects" field is an NSArray in Parse.
let subjects = Set(currentuser?.objectForKey("Subjects"))
Basically the syntax is correct, but the compiler (and me too) doesn't know that the object for key Subjects is supposed to be an array. Use optional binding to check at least for an array of NSObject to conform to the requirement that the items in the array are hashable (thanks to dan for pointing that out):
if let userSubjects = currentuser?.objectForKey("Subjects") as? [NSObject] {
let subjects = Set(userSubjects)
}
If the real type of Subjects is more specific than [NSObject] use that instead
When I am trying to take the value from a plist and append it to an array
nameArray.append(namesArray!.objectForKey("Item1")! as! String)
The target item is a string but it appears to be inside the plist array, can anyone explain how to get it out please?
The print of namesArray!.objectForKey("Item1")! followed by the error are shown below:
Cast the value of the "Item1" key as an array of Strings, then fetch the first object from the array (since it appears there's only one). And if you like the idea that your app should not crash everytime a value is nil, better use if let than force-unwrapping everything with !.
Example:
if let names = namesArray,
let items = names.objectForKey("Item1") as? [String],
let result = items.first {
nameArray.append(result)
}
Just take the first element of your array:
nameArray.append((namesArray!.objectForKey("Item1")! as! [String])[0])