Grab the highest date inside of an array of entities. - ios

I have the following array :
let messages = (fetchedResultsController.fetchedObjects as! [Message])
essentially, each element in this array is of the entity Message, where each Message has 5 core data attributes. Notably, the attribute I care about in this case is timestamp which is of type NSDate !!!!!!. I want to grab the message with the maximum date inside of this array using the reduce function. Please do not suggest to sort the messages first. I'am trying to avoid that. Thank you !

Not sure why you would want to use reduce, but I think this will work and fits with what you are looking for (assuming Swift 3):
let result = messages.max(by: {$0.timeStamp < $1.timeStamp})

Related

How do I remove double square brackets in ruby on rails?

After converting sql query from mysql object to json format I am getting array and I want only integer part from the array. Please let me know how can I achieve that.
query = "select count(priority) from table_complaint"
data = ActiveRecord::Base.connection(query).to_json
result is [[55]]
After executing above query I am getting results as [[integer]]
Now I want only integer/float part from the above array. Please help me out
You could take the first element of the outer array, which will be the inner array, and then the first element of that.
[[55]][0][0]
You might find the MiniSQL gem to be useful, but I wonder why you do not:
data = TableComplaint.count

Swift - Is there any way I can filter closer values from an array

I got an array of location objects. ( latitude , longitude, location name).
Location is received from users gps from morning to evening.
Challenge:
I want to create trip by filtering the location objects.
For e.g.: trip 1 will contain location from one start point to another and trip 2 will contain...
User can make 2/3 trips per day.
Question:
How can I group that array containing closer(values) latitudes and longitudes in swift iOS ?
EDIT
Get the data from array if the user is traveling else leave them so that from that array i can make a trip
Any ideas highly appreciated.
I think there is no way like magic code in swift for that.
How I actually solve is by traditional solving technique.
I did made a for loop and inside made a checker (which checked if two consecutive elements got time interval > 30 minutes then add the collected array elements as object to main array .
If anyone searching for such then apply you own logic.
var closure:((_ sender:UIButton)->())? = nil
var closure:((_ sender:UIButton)->())? = nil
closure!(sender)
cell.closure = { (sender:UIButton) -> Void in
debugPrint("\(indexPath.row + 1)")
debugPrint(sender.tag)
}

Filter on first letter of property

I've got a local db (Realm) with drinks. Each drink has a name.
I want to get all the drinks starting with a certain letter.
This is what I came up with:
let objects = realm.objects(Drank.self)
.filter{($0.name.characters.first)?.description == section}
The problem I am having now is that the objecttype I get is a 'LazyFilterBidirectionalCollection'. But I need Results.
Does anybody know a way to convert it to the correct type or maybe a different way to filter the resultset?
This is straight from the realm docs on sorting/filtering:
let sortedDogs = realm.objects(Dog.self).filter("color = 'tan' AND name BEGINSWITH 'B'").sorted(byProperty: "name")
So to filter something you are looking for maybe something like this:
let objects = realm.objects(Drank.self)
.filter("name BEGINSWITH '\(column)'")
A safer option proposed below by Thomas Goyne,
let objects = realm.objects(Drank.self)
.filter("name BEGINSWITH %#", column)
Since you are now filtering data with the way the docs use you should receive a Results object
Don't be afraid to read documentation, not only will you be able to get the satisfaction of figuring it out on your own, you will also learn a bunch of other things along the way.

Most efficient way of storing data which can be accessed and changed by all users

I'm currently in the process of learning both Swift and Parse and for the question I'm asking I'm going to use a simple up vote on a cell.
So I've got a table view controller which is populated by a query to a table on Parse. To do this I create a query on the relevant table and then store the bits of information into arrays e.g. an array for usernames, and text posts and object ID's:
var postGrabber: [PFObject] = [PFObject]()
var pSenderUsername: [String] = [String]()
var pPostBody: [String] = [String]()
var objectId: [String] = [String]()
I can then use the indexPath of a cell to get the relevant information from the arrays above.
Each cell also has a UIButton (for casting a vote as well as other information).
To get the indexPath of which cell has been clicked I use:
let btnPos: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: btnPos)!
let rowToAction = indexPath.first!
As a side note, objectAtIndexPath(rowToAction) does not seem to work in Swift 3, does anyone know of an alternative?
From this point I'm a little unsure of the most efficient way of updating my Parse table's score attribute.
After looking at the Parse docs, I could potentially use a counter variable to save a score or an array.
Though, I think if that there could be syncronization issues in using a counter in the case that multiple users are trying to access the data at any one given time. (Unsure)
Is it possible that someone could share their way of doing such a task possibly so that the data from Parse can only be accessed by 1 user at any 1 given time to avoid such issues.
So you want to increment the numberOfUpVotes.
You can use
[post incrementKey:#"numberOfUpVotes"];
[post saveInBackground];
This will update the votes asynchronously, and the incrementKey method is atomic. Let's say we have 5 users clicking on the "up" button at the same time, the value for key "numberOfUpVotes" will be 5 in stead of 1.
Also, you can specify your increment amount by :
[post incrementKey:#"numberOfUpVotes" byAmount:[NSNumber numberWithInt:2]]
But I don't think this is gonna happen in your use case :)
You can read this post from Parse:
https://parse.com/questions/concurrency-management-in-parse
or you can see my question:
iOS Parse.com updating objects
note: my code is in Objective-C, but it's pretty easy to convert that
into Swift.

Sqlite.swift filter/lookup

I'm using https://github.com/stephencelis/SQLite.swift to implement SQLite in swift. I read through the documentation but couldn't find what's the return type for filter specifically here
https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#filtering-rows
The reason I'm asking is because I have a table called userTable containing all usernames, emails... of all users, but how can I lookup if a specific user exist?
For the filter function, I have no idea what Table.filter return type is if there is nothing found that's matching the condition.
Specifically if "bob01" is not in the table then what would
table.filter(username=="bob01")
return?
Thanks!
If you want to select data from table you can use "prepare" or "pluck" methods of library. When you write "table.filter(...)", you actually define a query. So you should give this query to one of the above functions.
Different of these functions are return type. "Prepare" returns an Array includes Row type and "Pluck" returns Row. And finally, Row is a class that comes with SQLite.swift library.
let query = table.filter(username=="bob01")
var row = try db!.pluck(query) //it's optional
There is a video about it but it's in Turkish language: https://www.youtube.com/watch?v=cXA6ehpli5I
Also there is a part of code on my github: https://github.com/sercan5534/swift-lesson/blob/master/Swift-DB-Operations/SQLiteTest/DBUtil.swift

Resources