Finding sum of elements in Swift array

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

    Swift3 has changed to :

    let multiples = [...]
    sum = multiples.reduce(0, +)
    
    0 讨论(0)
  • 2020-11-30 18:51

    Swift 4 example

    class Employee {
        var salary: Int =  0
        init (_ salary: Int){
            self.salary = salary
        }
    }
    
    let employees = [Employee(100),Employee(300),Employee(600)]
    var sumSalary = employees.reduce(0, {$0 + $1.salary}) //1000
    
    0 讨论(0)
  • 2020-11-30 18:51

    How about the simple way of

    for (var i = 0; i < n; i++) {
     sum = sum + Int(multiples[i])!
    }
    

    //where n = number of elements in the array

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

    This is the easiest/shortest method I can find.

    Swift 3 and Swift 4:

    let multiples = [...]
    let sum = multiples.reduce(0, +)
    print("Sum of Array is : ", sum)
    

    Swift 2:

    let multiples = [...]
    sum = multiples.reduce(0, combine: +)
    

    Some more info:

    This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.

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