Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SWIFT

average in array swift

extension Array where Element: BinaryInteger {

    /// The average value of all the items in the array
    var average: Double {
        if self.isEmpty {
            return 0.0
        } else {
            let sum = self.reduce(0, +)
            return Double(sum) / Double(self.count)
        }
    }

}

extension Array where Element: BinaryFloatingPoint {

    /// The average value of all the items in the array
    var average: Double {
        if self.isEmpty {
            return 0.0
        } else {
            let sum = self.reduce(0, +)
            return Double(sum) / Double(self.count)
        }
    }

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #average #array #swift
ADD COMMENT
Topic
Name
5+6 =