Finding sum of elements in Swift array

后端 未结 16 1500
耶瑟儿~
耶瑟儿~ 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:28

    Keep it simple...

    var array = [1, 2, 3, 4, 5, 6, 7, 9, 0]
    var n = 0
    for i in array {
        n += i
    }
    print("My sum of elements is: \(n)")
    

    Output:

    My sum of elements is: 37

    0 讨论(0)
  • 2020-11-30 18:31

    Swift 3.0

    i had the same problem, i found on the documentation Apple this solution.

    let numbers = [1, 2, 3, 4]
    let addTwo: (Int, Int) -> Int = { x, y in x + y }
    let numberSum = numbers.reduce(0, addTwo)
    // 'numberSum' == 10
    

    But, in my case i had a list of object, then i needed transform my value of my list:

    let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })
    

    this work for me.

    0 讨论(0)
  • 2020-11-30 18:31

    this is my approach about this. however I believe that the best solution is the answer from the user username tbd

    var i = 0 
    var sum = 0
    let example = 0
    for elements in multiples{
        i = i + 1
        sum = multiples[ (i- 1)]
        example = sum + example
    }
    
    0 讨论(0)
  • 2020-11-30 18:32

    Swift 3

    If you have an array of generic objects and you want to sum some object property then:

    class A: NSObject {
        var value = 0
        init(value: Int) {
           self.value = value
        }
    }
    
    let array = [A(value: 2), A(value: 4)]      
    let sum = array.reduce(0, { $0 + $1.value })
    //                           ^       ^
    //                        $0=result  $1=next A object
    print(sum) // 6 
    

    Despite of the shorter form, many times you may prefer the classic for-cycle:

    let array = [A(value: 2), A(value: 4)]
    var sum = 0
    array.forEach({ sum += $0.value}) 
    // or
    for element in array {
       sum += element.value
    }
    
    0 讨论(0)
  • 2020-11-30 18:37

    Swift 3+ one liner to sum properties of objects

    var totalSum = scaleData.map({$0.points}).reduce(0, +)
    

    Where points is the property in my custom object scaleData that I am trying to reduce

    0 讨论(0)
  • 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 += <T:Number> (inout left: T, right: T)
    {
       left = left + right
    }
    
    prefix operator +/ {}
    
    prefix func +/ <T:Number>(ar:[T]?) -> T?
    {
        switch true
        {
        case ar == nil:
            return nil
    
        case ar!.isEmpty:
            return nil
    
        default:
            var result = ar![0]
            for n in 1..<ar!.count
            {
                result += ar![n]
            }
            return result
       }
    }
    

    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)

    0 讨论(0)
提交回复
热议问题