## SOLVED: Code review of median calculator

 Apr '22 Hey, I'm slowly starting to write some algorithms in swift and so i coded a median calculator, that simply give out the median of an array. The idea behind it is to first sort the array in then print out the middle index of the array. I would like if someone of coulc criticize my code. Thankful, Felix! ``````func calcMedian(givenArray: Array) -> Any{ var indexOfMiddle: Int var sortedArray = givenArray.sorted() var arrayLength = givenArray.count indexOfMiddle = arrayLength / 2 return String(sortedArray[indexOfMiddle]) }`````` Apr '22 From a coding point of view, there are a few things that you will need to consider. What if `givenArray` is empty, how should this be handled? var `sortedArray` and `var arrayLength` are never modified so they should be `let sortedArray` and `let arrayLength` As the input is an array of integers, why have the function return type as `Any`. Also why return a `String`? From a mathematical perspective consider what the median is when there are an even number of elements in the array? The median is the mean of the two numbers at the n/2 and (n/2 + 1) positions, when n (number of elements) is even. 1 Apr '22 @greenemberred thanks so much for your answer, i will try to fix these things. Thanks so much!

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Sponsor Hacking with Swift and reach the world's largest Swift community!