Finding sum of elements in Swift array

后端 未结 16 1660
耶瑟儿~
耶瑟儿~ 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条回答
  •  旧时难觅i
    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(_ keyPath: KeyPath) -> 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
    

提交回复
热议问题