I really like Swift. It was my first real language and I am still with it today. But I feel like I write some functions in almost every project I do. So here are some of the extensions I think Swift should have(Array Edition).

All of these will be made for array’s of Double’s, but can easily be changed to any other number type.

So here is the first one: The average. I really don’t know why this isn’t implemented. It is so simple and useful.

extension Array where Element == Double {
	    func average() -> Double {
	        let sum = self.reduce(0, +)
	        return sum/Double(self.count)
	    }
	}

And once we have the average we should also implement the median. It sorts the whole array and return:

Either the number at the count (-1 as array’s are zero-indexed) divided by 2, if the count is odd

Or the average of the two numbers in the middle of the array, if the count is even. This is quite nice, because we can use our previously programmed average function.

#swift #arrays #extension #function #statistics

Simple Array Function’s Swift Should Have
1.15 GEEK