Заставить мою функцию вычислять среднее значение массива Swift

Нет, вы не можете сделать это напрямую. Вам нужно написать класс оболочки вокруг Map<Class, Object>, чтобы обеспечить, чтобы Object был instanceof классом.

23
задан Leo Dabus 1 February 2019 в 21:11
поделиться

5 ответов

Вы должны использовать метод lower () для суммирования массива следующим образом:

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)
    }
}

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

Если вам нужно работать с Decimal типами, то общая сумма уже покрыта свойством расширения протокола Numeric, поэтому вам нужно только реализовать усредненное свойство:

extension Collection where Element == Decimal {
    var average: Decimal {
        return isEmpty ? 0 : total / Decimal(count)
    }
}
94
ответ дан Leo Dabus 1 February 2019 в 21:11
поделиться

В вашем коде есть ошибки:

//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)
7
ответ дан Christian Wörz 1 February 2019 в 21:11
поделиться

Простое среднее с фильтром, если необходимо (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)
2
ответ дан Ferenc Kiss 1 February 2019 в 21:11
поделиться

Swift 4.2

За простую элегантную простоту я люблю:

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

Пока мы на нем, другие приятные reduce операции на основе:

// 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, +)
}

Предоставлено: MathKit Адриана Гударта, в основном без изменений.


Cute Update:

Я нашел следующее в Язык программирования Swift :

В приведенном ниже примере вычисляется среднее арифметическое (также известно как среднее значение) для списка чисел любой длины:

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
1
ответ дан AmitaiB 1 February 2019 в 21:11
поделиться

Небольшой вкладыш, использующий старомодный Objective-C KVC, переведенный на Swift:

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

Вы также можете получить сумму:

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

Подробнее об этом давно забытом сокровище : https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/CollectionOperators.html

2
ответ дан Zaphod 1 February 2019 в 21:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: