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.
In this tutorial, learn how to find the sum of an array of elements.
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.
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
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
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts