Making my function calculate average of array Swift

十年热恋 提交于 2019-12-17 04:31:25

问题


I want my function to calculate the average of my Double type array. The array is called "votes". For now, I have 10 numbers.

When I call the average function to get the average of the array votes, it doesn't work.

Here's my code:

var votes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func average(nums: Double...) -> Double {
    var total = 0.0
    for vote in votes {
        total += vote
    }
    let votesTotal = Double(votes.count)
    var average = total/votesTotal
    return average
}

average[votes]

How do I call the average here to get the average?


回答1:


You should use the reduce() method to sum your array as follow:

Xcode 11 • Swift 5.1

extension Collection where Element: Numeric {
    /// Returns the total sum of all elements in the array
    var total: Element { reduce(0, +) }
}

extension Collection where Element: BinaryInteger {
    /// Returns the average of all elements in the array
    var average: Double { isEmpty ? 0 : Double(total) / Double(count) }
}

extension Collection where Element: BinaryFloatingPoint {
    /// Returns the average of all elements in the array
    var average: Element { isEmpty ? 0 : total / Element(count) }
}

let votes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let votesTotal = votes.total        // 55
let votesAverage = votes.average    // "5.5"

If you need to work with Decimal types the total sum it is already covered by the Numeric protocol extension property, so you only need to implement the average property:

extension Collection where Element == Decimal {
    var average: Decimal { isEmpty ? 0 : total / Decimal(count) }
}



回答2:


You have some mistakes in your code:

//You have to set the array-type to Double. Because otherwise Swift thinks that you need an Int-array
var votes:[Double] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func average(nums: [Double]) -> Double {

    var total = 0.0
    //use the parameter-array instead of the global variable votes
    for vote in nums{
        total += Double(vote)
    }

    let votesTotal = Double(nums.count)
    var average = total/votesTotal
    return average
}

var theAverage = average(votes)



回答3:


Simple avarage with filter if needed (Swift 4.2):

let items: [Double] = [0,10,15]
func average(nums: [Double]) -> Double {
    let sum = nums.reduce((total: 0, elements: 0)) { (sum, item) -> (total: Double, elements: Double) in
        var result = sum
        if item > 0 { // example for filter
            result.total += item
            result.elements += 1
        }

        return result
    }

    return sum.elements > 0 ? sum.total / sum.elements : 0
}
let theAvarage = average(nums: items)



回答4:


A small one liner, using old fashioned Objective-C KVC translated in Swift:

let average = (votes as NSArray).value(forKeyPath: "@avg.floatValue")

You can also have the sum:

let sum = (votes as NSArray).value(forKeyPath: "@sum.floatValue")

More on this long forgotten gem : https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/CollectionOperators.html




回答5:


Swift 4.2

For sheer elegant simplicity, I love:

// 1. Calls #3
func average <T> (_ values: T...) -> T where T: FloatingPoint
{
    return sum(values) / T(values.count)
}

While we're at it, other nice reduce-based operations:

// 2. Unnecessary, but I appreciate variadic params. Also calls #3.
func sum <T> (_ values: T...) -> T where T: FloatingPoint
{
    return sum(values)
}

// 3.
func sum <T> (_ values: [T]) -> T where T: FloatingPoint
{
    return values.reduce(0, +)
}

Credit: Adrian Houdart's MathKit, largely unchanged.


Cute Update:

I found the following in The Swift Programming Language:

The example below calculates the arithmetic mean (also known as the average) for a list of numbers of any length:

func arithmeticMean(_ numbers: Double...) -> Double {
   var total: Double = 0
   for number in numbers {
       total += number
   }
   return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers


来源:https://stackoverflow.com/questions/28288148/making-my-function-calculate-average-of-array-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!