So I have a bit of an insane "calculator" application. This question/idea came up while using this static function on my Position type to find what percentage a position will be liquidated (closed):
public static func calculateCutLossPct(_ orders: [Order]) -> Double
However, upon realizing I needed to take segments of orders: [Order] and run those calculations on arbitrary parts or slices of the array, I thought I might be lucky but as I guessed this doesn't work:
func calculateCutLossPct(using indices: Range<Int>) -> Double {
Position.calculateCutLossPct(position.orders[indices]
}
My first thought was "Ok, let's make Position.calculateCutLossPct generic!"
Now I think I don't like function overloading because that's (again I think) leaving swift to figure out what function to call at runtime. I'm open to suggestions for using overloading but I need efficient power consumption, speed, and lightweight. This application is going to be running a lot of computations over long arrays of orders so I assumed generics to be the right choice. And yes I totally realize most of my overhead will be in my implementation of the algorithms however, these calculations do get a little hairy and some functions call other functions to find the values they need so they can get started on their calculation and you probably get the gist, this doesn't seem to be the environment for utilizing overloading.
But now I'm very curious, what Collection Protocols should I use? Because....
This works:
static public func calculateCutLossPct<T: Sequence>(_ orders: T)
This works:
static public func calculateCutLossPct<T: RandomAccessCollection>(_ orders: T)
And this also works:
static public func calculateCutLossPct<T: Collection>(_ orders: T)
I guess my core issue is...how do I figure out what protocol to start generalizing functions and types with so that I have the option to specialize them further when the use cases arise?
TLDR: What collections protocol is most fundamental so I can continue to specialize code in the future for the use case as it appears and not focus too narrowly too soon?