A type with values that support multiplication.
- Xcode 9.0+
- Swift Standard Library
Numeric protocol provides a suitable basis for arithmetic on scalar values, such as integers and floating-point numbers. You can write generic methods that operate on any numeric type in the standard library by using the
Numeric protocol as a generic constraint.
The following example extends
Sequence with a method that returns an array with the sequence’s values multiplied by two.
With this extension, any sequence with elements that conform to
Numeric has the
doubling method. For example, you can double the elements of an array of doubles or a range of integers:
Conforming to the Numeric Protocol
Numeric protocol conformance to your own custom type, implement the required initializer and operators, and provide a
magnitude property using a type that can represent the magnitude of any value of your custom type.