使我的函数计算数组Swift的平均值

Luk*_*ivi 26 arrays function swift swift-playground

我希望我的函数计算我的Double类型数组的平均值.该数组称为"投票".现在,我有10个号码.

当我调用average function以获得阵列投票的平均值时,它不起作用.

这是我的代码:

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]
Run Code Online (Sandbox Code Playgroud)

我如何在此处调用平均值来获得平均值?

Leo*_*bus 97

您应该使用reduce()方法对数组求和如下:

Xcode 10•Swift 4.2

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

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

extension Collection where Element: BinaryFloatingPoint {
    /// Returns the average of all elements in the array
    var average: Element {
        return isEmpty ? 0 : total / Element(count)
    }
}
Run Code Online (Sandbox Code Playgroud)
let votes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let votesTotal = votes.total        // 55
let votesAverage = votes.average    // "5.5"
Run Code Online (Sandbox Code Playgroud)

如果您需要使用Decimal类型Numeric协议扩展属性已涵盖的总和,那么您只需要实现average属性:

extension Collection where Element == Decimal {
    var average: Decimal {
        return isEmpty ? 0 : total / Decimal(count)
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*örz 8

您的代码中有一些错误:

//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)
Run Code Online (Sandbox Code Playgroud)