Reputation: 165
I'm just learning Swift, and I was recently practicing with some code and I wanted to find an average of numbers in an array. Upon Googling it, I found tons of different examples... all approaching the problem differently. From just a couple lines of code, to very robust functions. Everyone had a different opinion, or a different angle. And this left me wondering:
Why are more basic math functions not built-in as a native function? OR, Why is there not some popular library that most people use to achieve this? (If there is one, please point me to it)
Admittedly, I only have experience in only a few languages, thus I don't know how common this is, or isn't. Or for that matter, if there's a good reason for it or not (there may be).
But in my experience, I've never had to write functions for avg() or sum(). I'm not saying it's hard. It's not. But it does seem grossly inefficient for me to spend time writing stuff like this. In C# (for example) you only need to include LINQ namespace which gives you access to the Average() extension method. In Python, you can import "statistics" module and use mean(). In PHP you at least get an array_sum() function natively thereby making the calculation of average fairly painless.
And that's just talking about sum() and avg(). What about other fairly simple math functions like min(), max() or even median()? Is everyone iterating over their arrays, or using reduce() (and in so doing making the code far less readable).
My question is simple... am I'm missing something? Or do all swift developers just write their own? This seems so inefficient to me.
Upvotes: 2
Views: 789
Reputation: 535850
min
and max
exist in Swift. If you have an array, use minElement
and maxElement
.
let i = min(2,1,3)
let i2 = [2,1,3].minElement()
Numerous other math functions, such as roots and powers and logs, rounding, and trig, exist in C, and these are directly available in Swift, so there is no point recreating them.
let x = sqrt(2.0)
To sum an array, use reduce
.
let sum = [2,1,3].reduce(0, combine:+)
Upvotes: 1