ProtocolSwift5.9.0

    AdditiveArithmetic

    A type with values that support addition and subtraction.

    protocol AdditiveArithmetic : Equatable

    The AdditiveArithmetic protocol provides a suitable basis for additive arithmetic on scalar values, such as integers and floating-point numbers, or vectors. You can write generic methods that operate on any numeric type in the standard library by using the AdditiveArithmetic protocol as a generic constraint.

    The following code declares a method that calculates the total of any sequence with AdditiveArithmetic elements.

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

    The sum() method is now available on any sequence with values that conform to AdditiveArithmetic, whether it is an array of Double or a range of Int.

    let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum()
    // arraySum == 16.5
    
    let rangeSum = (1..<10).sum()
    // rangeSum == 45

    Conforming to the AdditiveArithmetic Protocol

    To add AdditiveArithmetic protocol conformance to your own custom type, implement the required operators, and provide a static zero property.

    Supertypes

    Requirements

    Citizens in Swift

    Members

    Subtypes

    Extension in Atomics

    Subtypes

    • protocol AtomicInteger

      A type that supports atomic integer operations through a separate atomic storage representation.

    Extension in Durations

    Subtypes

    Extension in RealModule

    Members

    Subtypes