Sum an Array - Objective-C

前端 未结 3 798
我在风中等你
我在风中等你 2020-12-14 03:33

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

相关标签:
3条回答
  • 2020-12-14 03:57

    In Swift 4:

    let array = [1,2,3,5]
    let sum = array.reduce(0, {$0 + $1})
    print(sum)
    
    0 讨论(0)
  • 2020-12-14 03:58

    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.

    0 讨论(0)
  • 2020-12-14 04:18

    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];
    }
    
    0 讨论(0)
提交回复
热议问题