16

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

3 Answers 3

79

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Jeez, I did not know about @sum.self, wow, every day I am reminded of how much I don't know.
Interestingly there are such key also like "max.self", "min.self"... Awesome solution..
2

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.

2 Comments

I know you're doing it as an example of using keypaths, but for any newer Swift readers, you might want to use a reduce instead! let sum = numArray.reduce(0) { $0 + $1 }
@MikeSprague: I'm not disagreeing with you on which might be more appropriate, although I'm interested in your reasoning why an alternative method shouldn't be presented. The reason I like this method is that for the amount of code involved it works quite well for an array which contains mixed integers and string values.
-1

In Swift 4:

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

1 Comment

This is an Objective-C question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.