I'm modelling a time series log in Swift using just an Array
and a custom class that looks like:
class StatusEvent {
var status:ValveStatus // this is just an enum
var begin:NSDate
}
As I get updates to my log, I maintain the invariant that there are no duplicates (inferred by matching times) and that they are sorted in order by the begin
property. My three uses for this data are:
- Access the latest (last) element (this happens a lot)
- Enumerate them in order (for visualizing the time series)
- Adding new values to the list, which happens on periodic updates, but not that much
I can do some quick checks like "is this an add past end or before front" which take care of a lot of them, but when I detect the case where I've got to insert somewhere in the middle, I came up with the following:
var begin = oldestLogEvent.begin
for index in 1..<self.statusLog.count {
let event = self.statusLog[index]
let end = event.begin
if newEvent.begin == end {
return false;
}
if begin < newEvent.begin && newEvent.begin < end {
self.statusLog.insert(newEvent, atIndex: index)
return true;
}
begin = end;
}
I return a Bool
indicating whether an insertion happened or not.
Having ported this from Objective-C, I'm curious if Swift gives me some tools/idioms that would solve this "search for insertion point and conditionally insert" algorithm?
I'm open to using some other than an Array and simple event class; I looked at using a tree, but while that makes the insert potentially faster, I think it would cost more memory as well as make enumeration and last element access (my primary use cases) slower.