{

How to calculate the sum of all numbers or object values in Array swift with an example


 calculate the sum of all numbers or object values in Array swift with example

In this tutorial, learn how to find the sum of an array of elements.

  • array reduce method with primitive and objects of an array

The array can contain numbers or objects that contain numeric values.

Array reduce method that takes an array of elements, and returns a single value.

Sum of an array of numbers in Swift with examples

The array has a reduce method that reduces the array of elements into a single value.

Here is a code example for the swift 3 and 4 version

let numbers = [1,4,5,2,3,8]
let sum = numbers.reduce(0, +)
print("Sum of an array is : ", sum)

Output:

The Sum of an array is:  23

How to get the Sum of numbers of an Object Array in Swift

Let’s create a class Student, which contains marks and id fields.

Initialize the data to the Student object.

reduce method that takes a parameter and adds the result.

Here is an example to find the sum of property values of an object array in swift.

class Student {
    var marks: Int =  0
    var id: Int;
    init ( _ id: Int , _ marks: Int){
        self.marks = marks
        self.id=id
    }
}

let students = [Student(1,70),Student(2,50),Student(3,90)]
var result = students.reduce(0, {$0 + $1.marks}) 
print(result)
class Student {
    var marks: Int =  0
    var id: Int;
    init ( _ id: Int , _ marks: Int){
        self.marks = marks
        self.id=id
    }
}

let students = [Student(1,70),Student(2,50),Student(3,90)]
var index1 = students.firstIndex{ $0.id == 1 } as Any
print(index1)
var index2 = students.firstIndex{ $0.id == 6 } as Any
print(index2)

Output:

Optional(0)
nil
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.