protocol
SignedNumeric
A type that can represent both positive and negative values.
Inheritance | Numeric |
---|---|
Conforming Types | FloatingPoint, SignedInteger |
Instance Methods
Replaces this value with its additive inverse.
The following example uses the negate()
method to negate the value of
an integer x
:
var
x
=
21
x
.
negate
()
// x == -21
The resulting value must be representable within the value's type. In particular, negating a signed, fixed-width integer type's minimum results in a value that cannot be represented.
var
y
=
Int8
.
min
y
.
negate
()
// Overflow error
Declaration
mutating
func
negate
()
Type Methods
Returns the additive inverse of the specified value.
The negation operator (prefix -
) returns the additive inverse of its
argument.
let
x
=
21
let
y
= -
x
// y == -21
The resulting value must be representable in the same type as the argument. In particular, negating a signed, fixed-width integer type's minimum results in a value that cannot be represented.
let
z
= -
Int8
.
min
// Overflow error
Declaration
prefix
static
func
-(
operand
:
Self
) -
>
Self
The
SignedNumeric
protocol extends the operations defined by theNumeric
protocol to include a value's additive inverse.Conforming to the SignedNumeric Protocol
Because the
SignedNumeric
protocol provides default implementations of both of its required methods, you don't need to do anything beyond declaring conformance to the protocol and ensuring that the values of your type support negation. To customize your type's implementation, provide your own mutatingnegate()
method.When the additive inverse of a value is unrepresentable in a conforming type, the operation should either trap or return an exceptional value. For example, using the negation operator (prefix
-
) withInt.min
results in a runtime error.