让我的函数计算数组 Swift 的平均值 [英] Making my function calculate average of array Swift

查看:29
本文介绍了让我的函数计算数组 Swift 的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我调用average 函数 来获取数组投票的平均值时,它不起作用.

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

这是我的代码:

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?

推荐答案

你应该使用 reduce 方法来总结你的序列元素如下:

You should use the reduce method to sum your sequence elements as follow:

Xcode Xcode 10.2+ • Swift 5 或更高版本

extension Sequence where Element: AdditiveArithmetic {
    /// Returns the total sum of all elements in the sequence
    func sum() -> Element { reduce(.zero, +) }
}


extension Collection where Element: BinaryInteger {
    /// Returns the average of all elements in the array
    func average() -> Element { isEmpty ? .zero : sum() / Element(count) }
    /// Returns the average of all elements in the array as Floating Point type
    func average<T: FloatingPoint>() -> T { isEmpty ? .zero : T(sum()) / T(count) }
}


extension Collection where Element: BinaryFloatingPoint {
    /// Returns the average of all elements in the array
    func average() -> Element { isEmpty ? .zero : sum() / Element(count) }
}


let votes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let votesTotal = votes.sum()                       // 55
let votesAverage = votes.average()                 // 5
let votesDoubleAverage: Double = votes.average()   // 5.5


如果你需要使用 Decimal 输入它的总和,它已经被 AdditiveArithmetic 协议扩展方法覆盖了,所以你只需要实现平均值:


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

extension Collection where Element == Decimal {
    func average() -> Decimal { isEmpty ? .zero : sum() / Decimal(count) }
}



如果您需要对自定义结构的某个属性求和,我们可以扩展 Sequence 并创建一个以 KeyPath 作为参数来计算其总和的方法:



If you need to sum a certain property of a custom structure we can extend Sequence and create a method that takes a KeyPath as argument to calculate its sum:

extension Sequence  {
    func sum<T: AdditiveArithmetic>(_ predicate: (Element) -> T) -> T {
        reduce(.zero) { $0 + predicate($1) }
    }
}


用法:


Usage:

struct User {
    let name: String
    let age: Int
}

let users: [User] = [
    .init(name: "Steve", age: 45),
    .init(name: "Tim", age: 50)]

let ageSum = users.sum(\.age) // 95


并扩展集合以计算其平均值:


And extend collection to calculate its average:

extension Collection {
    func average<T: BinaryInteger>(_ predicate: (Element) -> T) -> T {
        sum(predicate) / T(count)
    }
    func average<T: BinaryInteger, F: BinaryFloatingPoint>(_ predicate: (Element) -> T) -> F {
        F(sum(predicate)) / F(count)
    }
    func average<T: BinaryFloatingPoint>(_ predicate: (Element) -> T) -> T {
        sum(predicate) / T(count)
    }
    func average(_ predicate: (Element) -> Decimal) -> Decimal {
        sum(predicate) / Decimal(count)
    }
}


用法:


Usage:

let ageAvg = users.average(\.age)                 // 47
let ageAvgDouble: Double = users.average(\.age)   // 47.5

这篇关于让我的函数计算数组 Swift 的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆