A type with values that support addition and subtraction.
SDK
- Xcode 10.2+
Framework
- Swift Standard Library
Declaration
Overview
The Additive
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 Additive
protocol as a generic constraint.
The following code declares a method that calculates the total of any sequence with Additive
elements.
The sum()
method is now available on any sequence with values that conform to Additive
, whether it is an array of Double
or a range of Int
.
Conforming to the AdditiveArithmetic Protocol
To add Additive
protocol conformance to your own custom type, implement the required operators, and provide a static zero
property using a type that can represent the magnitude of any value of your custom type.