Reputation: 1559
I have an array of dates that are in the form of strings, and I want to organize them by the oldest dates last. The circumstances are I have a list of dates(already organized), and I am inserting a date. For instance, I want to insert "08/23/2015"
in
["08/27/2015", "08/27/2015", "08/25/2015", "08/21/2015"]
So it appears at index 3.
I tried:
var id = -1
var index = datesArray.dates.count
let newDate = "08/23/2015"
let dDateStr = stringFromDate("08/23/2015")
let cDateStr = stringFromDate(NSDate())
if dDateStr != cDateStr {
while id < 0 && index > 0 {
if dateFromString(dDateStr).timeIntervalSinceNow >= dateFromString(destView.dates[index]).timeIntervalSinceNow {
id = index
}
index = index - 1
}
id = 0
}
else {
id = 0
}
datesArray.insert(newDate, atIndex: id)
Yet, it always gives me id = -1
. Any advice?
I am using Swift 1.2 on Xcode 6.4 for iOS 8
Upvotes: 2
Views: 501
Reputation: 57114
I changed your code quite a bit but it works now (changed because I partially did not understand what your code was supposed to do exactly.):
func dateFromString (string:String) -> NSDate {
let df = NSDateFormatter()
df.dateFormat = "MM/dd/yyyy"
return df.dateFromString(string)!
}
var datesArray = ["08/27/2015", "08/27/2015", "08/25/2015", "08/21/2015"]
var id = 0
var index = datesArray.count
let newDateString = "08/23/2015"
let newDate = dateFromString(newDateString).timeIntervalSinceNow
for index in 0..<datesArray.count {
if dateFromString(datesArray[index]).timeIntervalSinceNow >= newDate {
id = index + 1
}
}
datesArray.insert(newDateString, atIndex: id)
Please note that it still is not the most performant code possible.
But it outputs
3
and can insert at the first and last position as well.
You may have to change the array reference and stuff like that because I do not know in what way you are planning to include this snippet.
Upvotes: 2