开发者

Sum an Array - Objective-C

I'm just starting out and I'm looking for an easy way to sum a simple array. I've read into apple developer site on key value coding and I don't understand how to apply that to my array or if that's the appropriate way to sum this.

My stumbling block with the key value coding is the .keypathToProperty - I can sort of understand that you need a further reference in a 2D array but they don't show the array code, only the keypath to the title of the row so I can't figure it out yet.

NSMutableArray *numArray = [NSMutableArray arrayWithCapacity:4];
    [numArray addObject:num1];
    [numArray addObject:num2];  
    开发者_开发技巧[numArray addObject:num3];
    [numArray addObject:num4];

I appreciate the replies!

Thanks

Graham


The automatic way to do it is:

NSNumber * sum = [numArray valueForKeyPath:@"@sum.self"];

But if you're just starting out, I would recommend avoiding the collection key-path operators and go for the more simple way:

double sum = 0;
for (NSNumber * n in numArray) {
  sum += [n doubleValue];
}


Swift 3: (Dave DeLong's method transformed):

let sum = (numArray as AnyObject).value(forKeyPath:"@sum.self") as! Double

This should work in a similar fashion to it's Objective-C counterpart.


In Swift 4:

let array = [1,2,3,5]
let sum = array.reduce(0, {$0 + $1})
print(sum)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜