UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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])
}

2      

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.

3      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.