Finding sum of elements in Swift array

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

提交回复
热议问题