I created an array that contains different numbers and each time the button is clicked the array advances to the next index number.
var currentNumber = 0
var random = ["1", "2", "3", "4", "5", "6"]
#IBAction func numberUp(sender: UIButton)
numberLabel.text = random[currentNumber]
++currentNumber
I tried to get similar results in with Parse but i couldn't. I created a class with a array in it
var numbers = PFObject(className:"Numbers")
numbers["number"] = ["1","2","3","4","5","6"]
numbers.save()
How would i go about doing the same thing but with the array i created on Parse. Or how could i retrieve the array from Parse and assign it to a local array ?
First you have to create a PFQuery like
let query = PFQuery(className: "Numbers")
Create a query to download the data in the table:
let result = query.find()
Then assume you have only one row in the table:
let arrayOfNumbers = result.first
Then you can iterate on arrayOfNumbers
Related
I'm working on an IOS project that gets its data from Google's Firebase Firestore.
I have Documents like this in Firestore:
5lTSobXhcQBR2oG95s5q
Title: "ABC"
Timestamp: 1554374528.641053
FEeIAlAPlcrVvvtSKn8D
Title: "XYZ"
Timestamp: 1554443702.1300058
In my IOS project I have a Dictionary like this:
myDictionary: [String: [String: Any]] = [5lTSobXhcQBR2oG95s5q: ["Title": "ABC", "Timestamp": 1554374528.641053], FEeIAlAPlcrVvvtSKn8D: ["Title": "XYZ", "Timestamp": 1554443702.1300058]]
How can I sort my Dictionary by Timestamp?
If you are OK with getting back an array of tuples you can apply sorted() with a closure
let sortedTuples = myDictionary.sorted() {
if let t1 = $0.value["Timestamp"] as? Double, let t2 = $1.value["Timestamp"] as? Double {
return t1 < t2
}
return true
}
Note that I by default return true here if either of the values can't be cast to double or doesn't exist. A more advanced logic can of course be implemented depending on which of the two elements fails.
Every collection in iOS or swift has a sort function.
For example:
let sortedArray = dictionary.sort() { return $0.timestamp < $1.timestamp }
$0 will reference to 'the first' element and $1 the element after the first one.
In your example, the logic is the same.
I would do it like this:
Extract the timestamp data and store it in an extra dictionary with the id as a key and the value as a timestamp. Then I would use the .sort function to sort these elements in my dictionary.
I'm using firebase to store the amount of views every video in my app has been seen. What I want to is to gather all views from from one users all videos and display the total number of views. However I'm having problems fetching down the data and putting all the dictionary values together into a Int/String!
Ive tried many different solutions so far, but still I get all the different values in like array / values of the dictionary instead of everything added into one value
This is my code for getting all the videoviews of a specific user, no problems with this so far. When I print "intConvert" I get like all the views in different rows.
let ref = Database.database().reference().child("videoviews").child(stringUid)
ref.observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
let numbOfViews = dictionary["views"] as! String
let intConvert = Int(numbOfViews)!
let ArrayViews = [intConvert]
This is my database structure:
**videoviews**
-Lb52VxrEqdSRGljJdP7
views: "25"
-Lb53ARq_lOHEbTruW8s
views: "273"
-Lb53A_cEyX3CYc4mKYn
views: "38"
EDIT: If I do print(dictionary), the dictionary from "if let dictionary = snapshot.value as? [String: Anyobject] looks like this:
["views": 642]
["views": 660]
["views": 628]
["views": 630]
["views": 615]
["views": 3]
["views": 0]
["views": 2]
["views": 1]
Edit: (I was confused and forgot to add the bracelets, sorry for that.)
when I do I "print(dictionary.values) the console looks like this (the key values from different dictionaries):
[642]
[660]
[628]
[630]
[615]
[3]
[0]
[2]
[1]
I then tried to put this together in a loop like this:
var bLoader = 0.0
for hejArray in 0...ArreyViews.count-1{
bLoader += Double(Arrej[hejArray])
}
But when I print "bLoader" I still get all the views for every video in different rows instead of gathered in one value.
So what do I need to do put together all the values from different dictionaries in Firebase into one Variable?
I appreciate all help I can get with this, I can imagine it shouldn't be too hard but that im missing out on something.
EDIT /// I finally found the problem. the "StringUid" that I passed in have different amount of values and therefore the whole function would be called for 9 times if the videos of the user had the amount of 9. The solution that finally worked looked like this:
Global Array declaration:
var myArray = [String]()
Inside the function:
if let dictionary = snapshot.value as? [String: AnyObject]{
let numbOfViews = dictionary["views"] as! String
let intConvert = Int(numbOfViews)!
self.myArray.append(numbOfViews)
let intArray = self.myArray.map { Int($0)!}
let total = intArray.reduce(0, +)
self.totalViewsShower2.text = String(total)
Thank you in advance!
Update
If you can directly print the values from your dictionary like that then the solution might be as easy as
let total = dictionary.values.reduce(0, +)
or if values are strings you need to convert them to Int
let total = dictionary.values.reduce(0) {sum, value -> Int in return sum + (Int(value) ?? 0)}
If on the other hand they values are string but defined as Any you need an extra cast
let total2 = dictionary2.values.reduce(0) {sum, value -> Int in
if let str = value as? String {
return sum + (Int(str) ?? 0)
}
return 0
}
I am not exactly sure what your dictionary contains but I assumed something like this
let dictionary: [String: Any] = ["views": ["1", "2", "3"]]
Then you can cast the value for the "views" key to a String array and then use reduce on that array to get the sum
let array = dictionary["views"] as! [String]
let total = array.reduce(0) {sum, value -> Int in return sum + (Int(value) ?? 0)}
According to your Database structure which looks something like this
{
"videoviews": {
"Lb52VxrEqdSRGljJdP7": {
"views": "25"
},
"Lb53ARq_lOHEbTruW8s": {
"views": "273"
},
"Lb53A_cEyX3CYc4mKYn": {
"views": "38"
}
}
}
let ref = Database.database().reference().child("videoviews").child(stringUid)
ref.observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let viewsArray = dictionary.values
.compactMap { $0 as? [String: String] }
.compactMap { Int($0["views"] ?? "") }
let totalViews = viewsArray.reduce(0, +)
}
})
If I have the following array and I want to create a string array containing the door prizes by mapping the mysteryDoors array as keys for the dictionary, and get the corresponding values into a new array.
Thus I would get a string array of ["Gift Card", "Car", "Vacation"] how can I do that?
let mysteryDoors = [3,1,2]
let doorPrizes = [
1:"Car", 2: "Vacation", 3: "Gift card"]
You can map() each array element to the corresponding value in
the dictionary. If it is guaranteed that all array elements are
present as keys in the dictionary then you can do:
let mysteryDoors = [3, 1, 2]
let doorPrizes = [ 1:"Car", 2: "Vacation", 3: "Gift card"]
let prizes = mysteryDoors.map { doorPrizes[$0]! }
print(prizes) // ["Gift card", "Car", "Vacation"]
To avoid a runtime crash if a key is not present, use
let prizes = mysteryDoors.flatMap { doorPrizes[$0] }
to ignore unknown keys, or
let prizes = mysteryDoors.map { doorPrizes[$0] ?? "" }
to map unknown keys to a default string.
If you have to use map, then it would look something like the following:
let array = mysteryDoors.map { doorPrizes[$0] }
After re-reading the Apple Doc example code and changing it to what I need. I believe this is it (Almost). Unfortunately it is now in string format with new lines...
let myPrizes = doorPrizes.map { (number) -> String in
var output = ""
output = mysteryDoors[number]!
return output;
}
I want to implement a multiple click in my Shinobi DataGrid. I have a grid which have array
( ["1", "32", and more] )
If I click the grid I put it into new Array self.arrayNr.append(currNr).
But I want to check and remove if currNr is already exist in arrayNr it is will be remove from the arrayNr.
I'm new and using Swift 3. I read some question regarding with my question like this and this but it's not working. I think the Swift 2 is simpler than Swift 3 in handling for String. Any sugesstion or answer will help for me?
You can use index(of to check if the currNrexists in your array. (The class must conform to the Equatable protocol)
var arrayNr = ["1", "32", "100"]
let currNr = "32"
// Check to remove the existing element
if let index = arrayNr.index(of: currNr) {
arrayNr.remove(at: index)
}
arrayNr.append(currNr)
Say you have an array of string, namely type [String]. Now you want to remove a string if it exists. So you simply need to filter the array by this one line of code
stringArray= stringArray.filter(){$0 != "theValueThatYouDontWant"}
For example, you have array like this and you want to remove "1"
let array = ["1", "32"]
Simply call
array = array.filter(){$0 != "1"}
Long Solution
sampleArray iterates over itself and removes the value you are looking for if it exists before exiting the loop.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
for (index, value) in sampleArray.enumerated() {
if value == valueToCheck && sampleArray.contains(valueToCheck) {
sampleArray.remove(at: index)
break
}
}
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
Short Solution
sampleArray returns an array of all values that are not equal to the value you are checking.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
sampleArray = sampleArray.filter { $0 != valueToCheck }
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
I am trying to change my scripts to use the new google analytics API within Google Docs.
I am perfectly able to retrieve my data as an array from the api which might look like:
[["01", "5", "5"], ["02", "0", "0"], ["03", "2", "2"], ["04", "2", "6"], ["05", "46", "73"], ["06", "15", "18"], ["07", "7", "7"]]
Where I am looking for some help is on how to write this to a cell. I used to do so with the v2 API, but am struggling here. (just do not understand why my old method is not working).
What I would like to do:
Call a the function from a cell (randomly chosen)
drop the results from the array to a range in my sheet. The cell where I call the function should be the first cell to write the data.
The beginning of the function would be:
function testAnalytics() {
var id = "ga:XXXXXXXX";
var startdate = "2012-01-01";
var enddate = "2012-07-31";
var metrics = "ga:visits, ga:pageviews";
var optArgs = {dimensions: "ga:month"};
var grabData = Analytics.Data.Ga.get(id,startdate, enddate,metrics,optArgs);
// Browser.msgBox(grabData.getRows()); // test to see if data is correctly received
var returnVal = grabData.getRows();
return returnVal;
/* write returnVal to active cell on active spreadsheet */
}
Try
var sheet = SpreadsheetApp.getActiveSheet();
var thisCell = SpreadsheetApp.getActiveRange();
var row = thisCell.getRow();
var col = thisCell.getColumn();
//Assuming every row in the 2D array has the same number of elements.
sheet.getRange(row, col, returnVal.length , returnVal[0].length).setValues(returnVal);
If you want it to write to any other cell, change thisCell appropriately.
Note I haven't tested this myself so if there are syntax errors, please feel free to correct them :)