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.
用swift查找整数数组和最简单(最好)的方法是什么?我有一个被称为倍数的数组,我想知道倍数的和。
15 个解决方案
#1
296
This is the easiest/shortest method I can find.
这是我能找到的最简单/最短的方法。
Swift 3:
斯威夫特3:
let multiples = [...]
sum = multiples.reduce(0, +)
Swift 2:
斯威夫特2:
let multiples = [...]
sum = multiples.reduce(0, combine: +)
Some more info:
更多信息:
This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }
. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.
这使用了Array的reduce方法(这里的文档),它允许您“通过递归地应用提供的闭包,将元素集合减少到单个值”。我们给它0作为初始值,然后,本质上,闭包{$0 + $1}。当然,我们可以把它简化成一个加号,因为这就是快速滚动的方式。
#2
21
Swift 3 / Swift 4 one liner to sum properties of objects
Swift 3 / Swift 4一个行,用于对对象属性进行求和
var totalSum = scaleData.map({$0.points}).reduce(0, +)
Where points is the property in my custom object scaleData that I am trying to reduce
我要减少的自定义对象scaleData中的属性在哪里
#3
19
Swift3 has changed to :
Swift3已改为:
let multiples = [...]
sum = multiples.reduce(0, +)
#4
9
This also works:
这同样适用:
let arr = [1,2,3,4,5,6,7,8,9,10]
var sumedArr = arr.reduce(0, combine: {$0 + $1})
print(sumedArr)
The result will be: 55
结果将是:55
#5
5
How about the simple way of
那么简单的方法呢?
for (var i = 0; i < n; i++) {
sum = sum + Int(multiples[i])!
}
//where n = number of elements in the array
//其中n =数组中的元素个数
#6
4
Swift 3
斯威夫特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:
尽管形式较短,但很多时候你可能更喜欢经典的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
}
#7
4
Swift 4 example
斯威夫特4例
class Employee {
var salary: Int = 0
init (_ salary: Int){
self.salary = salary
}
}
let employees = [Employee(100),Employee(300),Employee(600)]
var sumSalary = employees.reduce(0, {$0 + $1.salary}) //1000
#8
2
A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)
一种可能的解决方案:为它定义一个前缀运算符。类似于APL中的reduce“+/”运算符(例如GNU APL)
A bit of a different approach here.
这里有一点不同的方法。
Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types
使用通用类型的协议允许我们在双、浮点和Int数组类型上使用该操作符
protocol Number
{
func +(l: Self, r: Self) -> Self
func -(l: Self, r: Self) -> Self
func >(l: Self, r: Self) -> Bool
func <(l: Self, r: Self) -> Bool
}
extension Double : Number {}
extension Float : Number {}
extension Int : Number {}
infix operator += {}
func += <T:Number> (inout left: T, right: T)
{
left = left + right
}
prefix operator +/ {}
prefix func +/ <T:Number>(ar:[T]?) -> T?
{
switch true
{
case ar == nil:
return nil
case ar!.isEmpty:
return nil
default:
var result = ar![0]
for n in 1..<ar!.count
{
result += ar![n]
}
return result
}
}
use like so:
使用像这样:
let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]
+/nmbrs // 548.1
+/intarr // 145
(updated for Swift 2.2, tested in Xcode Version 7.3)
(更新为Swift 2.2,在Xcode 7.3版本中测试)
#9
2
Swift 3.0
斯威夫特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.
这项工作对我来说。
#10
0
@IBOutlet var valueSource: [MultipleIntBoundSource]!
private var allFieldsCount: Int {
var sum = 0
valueSource.forEach { sum += $0.count }
return sum
}
used this one for nested parameters
将此参数用于嵌套参数
#11
0
In Swift 4 You can also extend the numeric type to return the sum of all elements in the collection as follow
在Swift 4中,还可以扩展数字类型,以返回集合中所有元素的总和,如下所示
extension Collection where Element: Numeric {
/// Returns the sum of all elements in the collection
func sum() -> Element { return reduce(0, +) }
}
let numbers = [1,2,3]
numbers.sum() // 6
let doubles = [1.5, 2.7, 3.0]
doubles.sum() // 7.2
#12
0
For sum of elements in array of Objects
用于对象数组中元素的和
self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)
#13
-1
Swift 3
斯威夫特3
From all the options displayed here, this is the one that worked for me.
从这里显示的所有选项中,这是对我有用的。
let arr = [6,1,2,3,4,10,11]
var sumedArr = arr.reduce(0, { ($0 + $1)})
print(sumedArr)
#14
-3
this is my approach about this. however I believe that the best solution is the answer from the user username tbd
这是我的方法。然而,我认为最好的解决方案是用户名tbd的答案。
var i = 0
var sum = 0
let example = 0
for elements in multiples{
i = i + 1
sum = multiples[ (i- 1)]
example = sum + example
}
#15
-3
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
我的元素和是:37。
#1
296
This is the easiest/shortest method I can find.
这是我能找到的最简单/最短的方法。
Swift 3:
斯威夫特3:
let multiples = [...]
sum = multiples.reduce(0, +)
Swift 2:
斯威夫特2:
let multiples = [...]
sum = multiples.reduce(0, combine: +)
Some more info:
更多信息:
This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }
. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.
这使用了Array的reduce方法(这里的文档),它允许您“通过递归地应用提供的闭包,将元素集合减少到单个值”。我们给它0作为初始值,然后,本质上,闭包{$0 + $1}。当然,我们可以把它简化成一个加号,因为这就是快速滚动的方式。
#2
21
Swift 3 / Swift 4 one liner to sum properties of objects
Swift 3 / Swift 4一个行,用于对对象属性进行求和
var totalSum = scaleData.map({$0.points}).reduce(0, +)
Where points is the property in my custom object scaleData that I am trying to reduce
我要减少的自定义对象scaleData中的属性在哪里
#3
19
Swift3 has changed to :
Swift3已改为:
let multiples = [...]
sum = multiples.reduce(0, +)
#4
9
This also works:
这同样适用:
let arr = [1,2,3,4,5,6,7,8,9,10]
var sumedArr = arr.reduce(0, combine: {$0 + $1})
print(sumedArr)
The result will be: 55
结果将是:55
#5
5
How about the simple way of
那么简单的方法呢?
for (var i = 0; i < n; i++) {
sum = sum + Int(multiples[i])!
}
//where n = number of elements in the array
//其中n =数组中的元素个数
#6
4
Swift 3
斯威夫特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:
尽管形式较短,但很多时候你可能更喜欢经典的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
}
#7
4
Swift 4 example
斯威夫特4例
class Employee {
var salary: Int = 0
init (_ salary: Int){
self.salary = salary
}
}
let employees = [Employee(100),Employee(300),Employee(600)]
var sumSalary = employees.reduce(0, {$0 + $1.salary}) //1000
#8
2
A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)
一种可能的解决方案:为它定义一个前缀运算符。类似于APL中的reduce“+/”运算符(例如GNU APL)
A bit of a different approach here.
这里有一点不同的方法。
Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types
使用通用类型的协议允许我们在双、浮点和Int数组类型上使用该操作符
protocol Number
{
func +(l: Self, r: Self) -> Self
func -(l: Self, r: Self) -> Self
func >(l: Self, r: Self) -> Bool
func <(l: Self, r: Self) -> Bool
}
extension Double : Number {}
extension Float : Number {}
extension Int : Number {}
infix operator += {}
func += <T:Number> (inout left: T, right: T)
{
left = left + right
}
prefix operator +/ {}
prefix func +/ <T:Number>(ar:[T]?) -> T?
{
switch true
{
case ar == nil:
return nil
case ar!.isEmpty:
return nil
default:
var result = ar![0]
for n in 1..<ar!.count
{
result += ar![n]
}
return result
}
}
use like so:
使用像这样:
let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]
+/nmbrs // 548.1
+/intarr // 145
(updated for Swift 2.2, tested in Xcode Version 7.3)
(更新为Swift 2.2,在Xcode 7.3版本中测试)
#9
2
Swift 3.0
斯威夫特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.
这项工作对我来说。
#10
0
@IBOutlet var valueSource: [MultipleIntBoundSource]!
private var allFieldsCount: Int {
var sum = 0
valueSource.forEach { sum += $0.count }
return sum
}
used this one for nested parameters
将此参数用于嵌套参数
#11
0
In Swift 4 You can also extend the numeric type to return the sum of all elements in the collection as follow
在Swift 4中,还可以扩展数字类型,以返回集合中所有元素的总和,如下所示
extension Collection where Element: Numeric {
/// Returns the sum of all elements in the collection
func sum() -> Element { return reduce(0, +) }
}
let numbers = [1,2,3]
numbers.sum() // 6
let doubles = [1.5, 2.7, 3.0]
doubles.sum() // 7.2
#12
0
For sum of elements in array of Objects
用于对象数组中元素的和
self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)
#13
-1
Swift 3
斯威夫特3
From all the options displayed here, this is the one that worked for me.
从这里显示的所有选项中,这是对我有用的。
let arr = [6,1,2,3,4,10,11]
var sumedArr = arr.reduce(0, { ($0 + $1)})
print(sumedArr)
#14
-3
this is my approach about this. however I believe that the best solution is the answer from the user username tbd
这是我的方法。然而,我认为最好的解决方案是用户名tbd的答案。
var i = 0
var sum = 0
let example = 0
for elements in multiples{
i = i + 1
sum = multiples[ (i- 1)]
example = sum + example
}
#15
-3
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
我的元素和是:37。