Finding sum of elements in Swift array

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

提交回复
热议问题