WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Code review of median calculator

Forums > Swift

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<Int>) -> Any{
    var indexOfMiddle: Int
    var sortedArray = givenArray.sorted()
    var arrayLength = givenArray.count
    indexOfMiddle = arrayLength / 2

    return String(sortedArray[indexOfMiddle])


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.


@greenemberred thanks so much for your answer, i will try to fix these things. Thanks so much!


Hacking with Swift is sponsored by Emerge

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.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.