Answers:
这是我能找到的最简单/最短的方法。
Swift 3和Swift 4:
let multiples = [...]
let sum = multiples.reduce(0, +)
print("Sum of Array is : ", sum)
斯威夫特2:
let multiples = [...]
sum = multiples.reduce(0, combine: +)
更多信息:
这使用了Array的reduce方法(在此处提供文档),该方法允许您“通过递归应用提供的闭包将元素的集合减少到单个值”。我们给它0作为初始值,然后本质上给闭包赋值{ $0 + $1 }
。当然,我们可以将其简化为单个加号,因为这就是Swift的滚动方式。
combine
。应该是multiples.reduce(0, combine: +)
。
flatMap
在其上将其展平为一个单一维度的数组。multiArray.flatMap{$0}.reduce(0, combine: +)
在Swift 4中,您还可以将序列元素约束为数字协议,以返回序列中所有元素的总和,如下所示
extension Sequence where Element: Numeric {
/// Returns the sum of all elements in the collection
func sum() -> Element { return reduce(0, +) }
}
编辑/更新:
Xcode 10.2•Swift 5或更高版本
我们可以简单地将序列元素限制为新的AdditiveArithmetic协议,以返回集合中所有元素的总和
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return reduce(.zero, +)
}
}
Xcode 11•Swift 5.1或更高版本
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element { reduce(.zero, +) }
}
let numbers = [1,2,3]
numbers.sum() // 6
let doubles = [1.5, 2.7, 3.0]
doubles.sum() // 7.2
这也适用:
let arr = [1,2,3,4,5,6,7,8,9,10]
var sumedArr = arr.reduce(0, combine: {$0 + $1})
print(sumedArr)
结果将是:55
迅捷3
如果您有一组通用对象,并且想要对一些对象属性求和,则:
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
尽管格式较短,但很多时候您可能更喜欢经典的for周期:
let array = [A(value: 2), A(value: 4)]
var sum = 0
array.forEach({ sum += $0.value})
// or
for element in array {
sum += element.value
}
简单的方法怎么样
for (var i = 0; i < n; i++) {
sum = sum + Int(multiples[i])!
}
// n =数组中的元素数
var sum = 0 ; for n in multiples { sum += n }
虽然我会使用减少。
一种可能的解决方案:为其定义前缀运算符。就像APL(例如GNU APL)中的reduce“ + /”运算符一样
这里有点不同的方法。
使用协议en泛型类型使我们可以在Double,Float和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
}
}
像这样使用:
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
(已针对Swift 2.2更新,并在Xcode 7.3版中进行了测试)
斯威夫特3.0
我遇到了同样的问题,我在Apple文档中找到了该解决方案。
let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10
但是,就我而言,我有一个对象列表,然后需要转换列表的值:
let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })
这项工作对我来说。
@IBOutlet var valueSource: [MultipleIntBoundSource]!
private var allFieldsCount: Int {
var sum = 0
valueSource.forEach { sum += $0.count }
return sum
}
使用这个作为嵌套参数
对我来说,就像这样使用属性
let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
result + participant.kills
})
对于对象数组中元素的总和
self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)
let totalSum = self.cheques.reduce(0) { $0 + $1.amount}