Finding sum of elements in Swift array

后端 未结 16 1639
耶瑟儿~
耶瑟儿~ 2020-11-30 18:12

What is the easiest (best) way to find the sum of an array of integers in swift? I have an array called multiples and I would like to know the sum of the multiples.

16条回答
  •  爱一瞬间的悲伤
    2020-11-30 18:37

    A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)

    A bit of a different approach here.

    Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types

    protocol Number 
    {
       func +(l: Self, r: Self) -> Self
       func -(l: Self, r: Self) -> Self
       func >(l: Self, r: Self) -> Bool
       func <(l: Self, r: Self) -> Bool
    }
    
    extension Double : Number {}
    extension Float  : Number {}
    extension Int    : Number {}
    
    infix operator += {}
    
    func +=  (inout left: T, right: T)
    {
       left = left + right
    }
    
    prefix operator +/ {}
    
    prefix func +/ (ar:[T]?) -> T?
    {
        switch true
        {
        case ar == nil:
            return nil
    
        case ar!.isEmpty:
            return nil
    
        default:
            var result = ar![0]
            for n in 1..

    use like so:

    let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
    let intarr = [1, 34, 23, 54, 56, -67, 0, 44]
    
    +/nmbrs     // 548.1
    +/intarr    // 145
    

    (updated for Swift 2.2, tested in Xcode Version 7.3)

提交回复
热议问题