我希望函数计算Double型数组的平均值。该数组称为“投票”。现在,我有10个号码。
当我致电average function以获取阵列投票的平均值时,它不起作用。
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]
我如何在此处称平均值以获得平均值?
您应该使用reduce()方法对数组求和,如下所示:
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 : Element(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协议扩展方法所涵盖,因此您只需要实现平均值:
Decimal
AdditiveArithmetic
extension Collection where Element == Decimal { func average() -> Decimal { isEmpty ? .zero : sum() / Decimal(count) } }
如果您需要对自定义结构的某个属性求和,我们可以扩展Sequence并创建一个以KeyPath作为参数来计算其总和的方法:
Sequence
extension Sequence { func sum<T: AdditiveArithmetic>(_ keyPath: KeyPath<Element, T>) -> T { reduce(.zero) { $0 + $1[keyPath: keyPath] } } }
用法:
let users: [User] = [ .init(name: "Steve", age: 45), .init(name: "Tim", age: 50)] let ageSum = users.sum(\.age) // 95
并扩展集合以计算其平均值:
extension Collection { func average<I: BinaryInteger>(_ keyPath: KeyPath<Element, I>) -> I { sum(keyPath) / I(count) } func average<I: BinaryInteger, F: BinaryFloatingPoint>(_ keyPath: KeyPath<Element, I>) -> F { F(sum(keyPath)) / F(count) } func average<F: BinaryFloatingPoint>(_ keyPath: KeyPath<Element, F>) -> F { sum(keyPath) / F(count) } func average(_ keyPath: KeyPath<Element, Decimal>) -> Decimal { sum(keyPath) / Decimal(count) } }
let ageAvg = users.average(\.age) // 47 let ageAvgDouble: Double = users.average(\.age) // 47.5