Finding sum of elements in Swift array

后端 未结 16 1502
耶瑟儿~
耶瑟儿~ 2020-11-30 18:12

What is the easiest (best) way to find the sum of an array of integers in swift? I have an array called multiples and I would like to know the sum of the multiples.

相关标签:
16条回答
  • 2020-11-30 18:38

    This also works:

    let arr = [1,2,3,4,5,6,7,8,9,10]
    var sumedArr = arr.reduce(0, combine: {$0 + $1})
    print(sumedArr)
    

    The result will be: 55

    0 讨论(0)
  • 2020-11-30 18:42

    In Swift 4 You can also constrain the sequence elements to Numeric protocol to return the sum of all elements in the sequence as follow

    extension Sequence where Element: Numeric {
        /// Returns the sum of all elements in the collection
        func sum() -> Element { return reduce(0, +) }
    }
    

    edit/update:

    Xcode 10.2 • Swift 5 or later

    We can simply constrain the sequence elements to the new AdditiveArithmetic protocol to return the sum of all elements in the collection

    extension Sequence where Element: AdditiveArithmetic {
        func sum() -> Element {
            return reduce(.zero, +)
        }
    }
    

    Xcode 11 • Swift 5.1 or later

    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
    

    To sum a property of a custom object we can extend Sequence to take a keypath with a generic value that conforms to AdditiveArithmetic as parameter:

    extension Sequence  {
        func sum<T: AdditiveArithmetic>(_ keyPath: KeyPath<Element, T>) -> T { reduce(.zero) { $0 + $1[keyPath: keyPath] } }
    }
    

    Usage:

    struct Product {
        let id: String
        let price: Decimal
    }
    
    let products: [Product] = [.init(id: "abc", price: 21.9),
                               .init(id: "xyz", price: 19.7),
                               .init(id: "jkl", price: 2.9)
    ]
    
    products.sum(\.price)  // 44.5
    
    0 讨论(0)
  • 2020-11-30 18:45

    For me, it was like this using property

        let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
            result + participant.kills
        })
    
    0 讨论(0)
  • 2020-11-30 18:46
    @IBOutlet var valueSource: [MultipleIntBoundSource]!
    
    private var allFieldsCount: Int {
        var sum = 0
        valueSource.forEach { sum += $0.count }
        return sum
    }
    

    used this one for nested parameters

    0 讨论(0)
  • 2020-11-30 18:48

    Swift 3

    From all the options displayed here, this is the one that worked for me.

    let arr = [6,1,2,3,4,10,11]
    
    
    var sumedArr = arr.reduce(0, { ($0 + $1)})
    print(sumedArr)
    
    0 讨论(0)
  • 2020-11-30 18:50

    For sum of elements in array of Objects

    self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)
    
    0 讨论(0)
提交回复
热议问题