So I'm trying to extend Swift's integer types with a few convenient functions that I use a lot, however I'm not clear on which protocols I should be extending.
As an example, let's say I want to implement a function for clamping a value (if it's less than a minimum set it to that, otherwise if it's greater than a maximum then set it to that instead). My first thought was to do something like this:
extension Int {
func clamp(minimum:Int, maximum:Int) {
if self < minimum { return minimum }
if self > maximum { return maximum }
return self
}
}
Bit of a simplistic example, but it illustrates the problem; if I want to now call this for a UInt
then naturally I can't, so I have to add an equivalent to UInt
, but that won't work for a UInt16
and so-on.
I thought that I could perhaps extend something higher up the chain, and use generics instead, however protocols such as IntegerType
can't seem to be extended.
So, is there somewhere more appropriate that I could put my extension(s)?
IntegerType
using generics and this way it would appear for all integer values. This seems much neater to me than an IntUtils class with a ton of static functions in it. – GilboaincreaseScore
function would NOT be a good extension for theInt
struct. I think indeed the scenario you described is a clear example where extensions should NOT be used. On the other handclamp
is something related to theInt
. So it would be a good example ofextension
for theInt
struct. Even better in Swift 2.0 we can extend protocols so we can add theclamp
function to theComparable
protocol. This allows us to defineclamp
at an higher level. And it’s beautiful because as soon as we conform toComparable
we get theclamp
method for free!... – Waynesplit
that in Swift 2.0 is implemented inside an extension of the protocolCollectonType
... – Wayne