Finding sum of elements in Swift array

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

提交回复
热议问题