什么是最简单(最好)的方法来找到一个数组的整数和在swift? 我有一个数组叫multiples我想知道这些倍数的和。


当前回答

@IBOutlet var valueSource: [MultipleIntBoundSource]!

private var allFieldsCount: Int {
    var sum = 0
    valueSource.forEach { sum += $0.count }
    return sum
}

用于嵌套参数

其他回答

Swift 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

这是我能找到的最简单/最短的方法。

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就是这样运行的。

一个可能的解决方案是:为它定义一个前缀操作符。 如APL中的略读“+/”运算符(例如GNU APL)

这里有一点不同的方法。

使用泛型类型协议允许我们在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 Version 7.3中测试)

另一种简单的方法:

let sumOfMultiples = ar.reduce(0) { x, y in x + y }          
print(sumOfMultiples)

斯威夫特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-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
}