protocol
AdditiveArithmetic
A type with values that support addition and subtraction.
Inheritance | Equatable |
---|---|
Conforming Types | Numeric |
Type Variables
The zero value.
Zero is the identity element for addition. For any value,
x + .zero == x
and .zero + x == x
.
Declaration
var
zero
:
Self
Type Methods
Adds two values and produces their sum.
The addition operator (+
) calculates the sum of its two arguments. For
example:
1
+
2
// 3
-
10
+
15
// 5
-
15
+ -
5
// -20
21.5
+
3.25
// 24.75
You cannot use +
with arguments of different types. To add values of
different types, convert one of the values to the other value's type.
Declaration
static
func
+(
lhs
:
Self
,
rhs
:
Self
) -
>
Self
Adds two values and stores the result in the left-hand-side variable.
Declaration
static
func
+=(
lhs
:
inout
Self
,
rhs
:
Self
)
Subtracts one value from another and produces their difference.
The subtraction operator (-
) calculates the difference of its two
arguments. For example:
8
-
3
// 5
-
10
-
5
// -15
100
- -
5
// 105
10.5
-
100.0
// -89.5
You cannot use -
with arguments of different types. To subtract values
of different types, convert one of the values to the other value's type.
Declaration
static
func
-(
lhs
:
Self
,
rhs
:
Self
) -
>
Self
Subtracts the second value from the first and stores the difference in the left-hand-side variable.
Declaration
static
func
-=(
lhs
:
inout
Self
,
rhs
:
Self
)
Default Implementations
Declaration
public
static
func
!=(
lhs
:
Self
,
rhs
:
Self
) -
>
Bool
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 theAdditiveArithmetic
protocol as a generic constraint.The following code declares a method that calculates the total of any sequence with
AdditiveArithmetic
elements.The
sum()
method is now available on any sequence with values that conform toAdditiveArithmetic
, whether it is an array ofDouble
or a range ofInt
.Conforming to the AdditiveArithmetic Protocol
To add
AdditiveArithmetic
protocol conformance to your own custom type, implement the required operators, and provide a staticzero
property using a type that can represent the magnitude of any value of your custom type.