Hi I just want remove repeated objects should be removed in dictionary I am populating it in tableView
Here my sample code in 'CellForRowAtIndexPath'
controller.titleName = dict["itemName"] as? String
my output:
{
itemName = test;
},
{
itemName = funny;
},
{
itemName = vv;
},
{
itemName = hhh;
},
{
itemName = west;
}
First, i think thing you are using array to make dict so before load tableview/collectionview delete all replicated object from your array.
There is one option you have to create NSSet from NSArray so in NSSet all replicated object automatically removed . and then from NSSet you have to create NSArray.
convert set from array as follow
var set = NSSet(array: myarray)
To convert array for set
var newarry = set.allObjects as NSArray
Just try this
let uniqueArr = Array(Set(dict.values))
For your question I have tried separately and I got the answer
var arr = [AnyObject]()
var arrAppend = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let array = ["one", "one", "two", "two", "three", "three"]
let uniqueValue = Array(Set(array))
print("The unique value is - \(uniqueValue)")
let dictTest = ["itemName":"test"]
let dictFunny = ["itemName":"funny"]
let dictVVV = ["itemName":"vvv"]
let dictHHH = ["itemName":"hhh"]
let dictWest = ["itemName":"west"]
let dictTT = ["itemName":"tt"]
let dictWest1 = ["itemName":"west"]
arr.append(dictWest1)
arr.append(dictTest)
arr.append(dictVVV)
arr.append(dictTT)
arr.append(dictWest)
arr.append(dictFunny)
arr.append(dictHHH)
print("Array Response: \(arr)")
for keyValue in arr as Array
{
let getDictValueFromArray = keyValue["itemName"] as! String
arrAppend.append(getDictValueFromArray)
}
let unique = Array(Set(arrAppend))
print("the result is-\(unique)")
}
The Output for unique is
the result is-["funny", "test", "west", "vvv", "hhh", "tt"]
Related
I have two arrays.
let array1 = ["Lahari", "Vijayasri"];
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"];
I want to remove the array1 elements in array2 and print the final array-like
result array = ["Ramya", "Keerthi"]
Converting the arrays to Sets and using subtract is a simple and efficient method:
let array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let resultArray = Array(Set(array2).subtracting(Set(array1)))
If maintaining the order of array2 is important then you can use filter with a set -
let compareSet = Set(array1)
let resultArray = array2.filter { !compareSet.contains($0) }
Paulw11 answer works perfectly. But if ordering in array is important you can do this:
let reuslt = array2.filter { !array1.contains($0) }
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.subtracting(otherSet))
}
}
var array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let a = array2.difference(from: array1) // ["Ramya", "Keerthi"]
Only take the end.
array2[array1.count...]
I want to create array of array
ex-
let myImages: [[String]] = [
["image_url_0_0", "image_url_0_1", "image_url_0_2", "image_url_0_3"],
["image_url_1_0", "image_url_1_1", "image_url_1_2"],
["image_url_2_0", "image_url_2_1", "image_url_2_2", "image_url_2_3", "image_url_2_4"]
]
I tried this, but it doesn't work perfectly.
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
var arrImage: [String] = []
for customParams in custom_attributes! {
if let attCode = customParams["attribute_code"] as? String, attCode == "small_image" {
print(customParams["value"])
var myString = customParams["value"] as! String
arrImage.append(myString)
}
}
myArray.append(arrImage)
}
But I get result in this form
[["image_url_0_0"], ["image_url_0_0","image_url_0_1"], ["image_url_0_0","image_url_0_1","image_url_0_3"].....]
How should I do this?Please Help.
You try this
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
let arr : [String] = []
for customParams in custom_attributes! {
if(customParams["attribute_code"] as! String == "small_image")
{
print(customParams["value"])
var myString = customParams["value"] as! String
arr.append(myString)
}
}
myArray.append(arr)
}
First you need to create simple string array and then append this array to your myArray. Check following code may be it's help
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
var arrImage: [String] = []
for customParams in custom_attributes! {
if let attCode = customParams["attribute_code"] as? String, attCode == "small_image" {
print(customParams["value"])
var myString = customParams["value"] as! String
arrImage.append(myString)
}
}
myArray.append(arrImage)
}
I am getting values from and Array[String:Any] type array in a for loop but it is getting crashed when going on first line in for loop .
Actually I have created an array (Array[String:Any]) Type and now I am getting all the values of this array to show on tableview but it is getting crash in for loop.
var ticketArray = [Any]()
var addTypeTicket = [String:Any]()
var imagesArray = [Any]()
var imagesFinal = [String:Any]()
let ticketDetails = ["ticketName":txtTicketName.text!,
"numberOfTicketOnSale":txtFldTotalQuantityofTicket.text!,
"ticketPrice":txtFldPriceofTicket.text!,
"messageForTicketBuyers":txtviewMessage.text!,
"ticketGroupName":txtFldGroupName.text!] as [String : Any]
ticketArray.append(ticketDetails)
print(ticketArray)
addTypeTicket["addTypeTicket"] = ticketArray
print(addTypeTicket)
viewShadowTicket.isHidden = true
viewForMainTicketAlert.isHidden = true
for alltickets in addTypeTicket {
let ticketName = (alltickets as AnyObject).object(forKey: "ticketName") as! String
let Quantity = (alltickets as AnyObject).object(forKey: "numberOfTicketOnSale") as! String
let ticketPrice = (alltickets as AnyObject).object(forKey: "ticketPrice") as! String
let arr = structTickets(ticketName: ticketName, numberOfTicketOnSale: Quantity, ticketPrice: ticketPrice)
self.arrayTickets.append(arr)
}
self.tableview.reloadData()
tableview.isHidden = false
I just want to get values in for loop .
If you are not using ticketArray anywhere else then there is not need to add data to that array. You can simply add data to addTypeTicket dictionary by:
addTypeTicket["addTypeTicket"] = ticketDetails
Then you can fetch the data like this:
if let addTypeTicketData = addTypeTicket["addTypeTicket"] as? [String: String] {
let ticketName = addTypeTicketData["ticketName"]
let quantity = addTypeTicketData["numberOfTicketOnSale"]
let ticketPrice = addTypeTicketData["ticketPrice"]
let arr = structTickets(ticketName: ticketName, numberOfTicketOnSale: quantity, ticketPrice: ticketPrice)
self.arrayTickets.append(arr)
}
And use arrayTickets for tableView's numberOfRowsInSection.
I'm new to Swift. I have been having trouble downloading Firebase dictionaries and turning them into an array of objects.
What am I doing wrong with the syntax below? I've spent the last two days unsuccessfully trying to figure this out. The following gives me an index out of range error. Is this because the Firebase Dictionary hasn't finished downloading yet or is my for in loop sytax flawed? Perhaps both? Thanks.
// Array of Location Objects
var locationsArray:[Location] = [Location]()
var ref = Firebase(url: "<MYFIREBASEURL>")
var dictionaryOfRecommendations:[NSDictionary] = [NSDictionary]()
var currentlyConstructingLocation:Location = Location()
func getLocationData() {
let titleRef = self.ref.childByAppendingPath("events")
titleRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
var tempDict = [NSDictionary]()
for item in snapshot.children {
let child = item as! FDataSnapshot
let dict = child.value as! NSDictionary
tempDict.append(dict)
}
self.dictionaryOfRecommendations = tempDict
})
// Parse data from Firebase
// Loop through each dictionary and assign values to location object
var index:Int
for index in 0...dictionaryOfRecommendations.count {
// Current Json dictionary
let jsonDictionary:NSDictionary = self.dictionaryOfRecommendations[index]
self.currentlyConstructingLocation.title = jsonDictionary["title"] as! String!
self.currentlyConstructingLocation.locationsLatitudeArray = jsonDictionary["latitude"] as! Double
self.currentlyConstructingLocation.locationsLongitudeArray = jsonDictionary["longitude"] as! Double
// Append to Locations Array and start new Location
self.locationsArray.append(currentlyConstructingLocation)
self.currentlyConstructingLocation = Location()
}
// Notify the MainViewController that the Locations are ready.
...
}
Here's the updated correct code for the question above based on Jay's helpful guidance:
// Model to download location data for events.
//Firebase reference
var ref = Firebase(url: "<MYFIREBASEURL")
var locationsArray:[Location] = [Location]()
var dictionaryOfRecommendations:[NSDictionary] = [NSDictionary]()
var currentlyConstructingLocation:Location = Location()
func getLocationData() {
let titleRef = self.ref.childByAppendingPath("events")
titleRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
var tempDict = [NSDictionary]()
for item in snapshot.children {
let child = item as! FDataSnapshot
let dict = child.value as! NSDictionary
tempDict.append(dict)
}
self.dictionaryOfRecommendations = tempDict
self.ParseFirebaseData()
})
}
func ParseFirebaseData() {
// Parse data from Firebase
// Loop through each dictionary and assign values to location object
var index:Int
for index in 0...dictionaryOfRecommendations.count - 1 {
// Current Json dictionary
let jsonDictionary:NSDictionary = self.dictionaryOfRecommendations[index]
self.currentlyConstructingLocation.title = jsonDictionary["title"] as! String!
self.currentlyConstructingLocation.locationsLatitudeArray = jsonDictionary["latitude"] as! Double
self.currentlyConstructingLocation.locationsLongitudeArray = jsonDictionary["longitude"] as! Double
// Append to Locations Array and start new Location
self.locationsArray.append(currentlyConstructingLocation)
self.currentlyConstructingLocation = Location()
}
}
I have stored my contacts as a dictionary on an mutable array by this method:
var addressBookReff: ABAddressBookRef = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
var arrOfDictContacts:NSMutableArray = NSMutableArray()
let people:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBookReff).takeRetainedValue()
for person in people{
if let name:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
let numbers:ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
if let number:String = ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String {
arrOfDictContacts.addObject(["\(name)":"\(number)"])
}
}
}
Here, arrOfDictContacts is my mutable array which contains name and number as dictionary. Like this :
arrOfDictContacts = ({ my = 12131;}, { doctor = 54445;}, { AL = 543212601;}, { customer = 121; } }
Now I have another array of names as
arrOfNames = [my, AL]
I want to get the respective numbers of the arrOfNames from arrOfDictContacts
ExpectedOutput :
arrOfNumbers = [12131, 543212601]
How can I do this?
Edit:
Since your array contains dictionaries, the way to do it is to check each of the dictionaries against your array. Like following:
var arrOfNumbers : [String] = []
for dict in arrOfDictContacts {
for name in arrOfNames {
if let value = dict[name] as? String {
arrOfNumbers.append(value)
}
}
}