Numeric

protocol Numeric

A type with values that support multiplication.

Inheritance AdditiveArithmetic, ExpressibleByIntegerLiteral
Conforming Types BinaryInteger, SignedNumeric
Associated Types
associatedtype Magnitude

The 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.

extension Sequence where Element: Numeric {
    func doublingAll() -> [Element] {
        return map { $0 * 2 }
    }
}

With this extension, any sequence with elements that conform to Numeric has the doublingAll() method. For example, you can double the elements of an array of doubles or a range of integers:

let observations = [1.5, 2.0, 3.25, 4.875, 5.5]
let doubledObservations = observations.doublingAll()
// doubledObservations == [3.0, 4.0, 6.5, 9.75, 11.0]

let integers = 0..<8
let doubledIntegers = integers.doublingAll()
// doubledIntegers == [0, 2, 4, 6, 8, 10, 12, 14]

Conforming to the Numeric Protocol

To add 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.

Initializers

init init?(exactly:) Required

Creates a new instance from the given integer, if it can be represented exactly.

If the value passed as source is not representable exactly, the result is nil. In the following example, the constant x is successfully created from a value of 100, while the attempt to initialize the constant y from 1_000 fails because the Int8 type can represent 127 at maximum:

let x = Int8(exactly: 100)
// x == Optional(100)
let y = Int8(exactly: 1_000)
// y == nil
  • Parameter source: A value to convert to this type.

Declaration

init?<T>(exactly source: T) where T: BinaryInteger

Instance Variables

var magnitude Required

The magnitude of this value.

For any numeric value x, x.magnitude is the absolute value of x. You can use the magnitude property in operations that are simpler to implement in terms of unsigned values, such as printing the value of an integer, which is just printing a '-' character in front of an absolute value.

let x = -200
// x.magnitude == 200

The global abs(_:) function provides more familiar syntax when you need to find an absolute value. In addition, because abs(_:) always returns a value of the same type, even in a generic context, using the function instead of the magnitude property is encouraged.

Declaration

var magnitude: Self.Magnitude

Type Methods

func *(lhs: Self, rhs: Self) -> Self Required

Multiplies two values and produces their product.

The multiplication operator (*) calculates the product of its two arguments. For example:

2 * 3                   // 6
100 * 21                // 2100
-10 * 15                // -150
3.5 * 2.25              // 7.875

You cannot use * with arguments of different types. To multiply values of different types, convert one of the values to the other value's type.

let x: Int8 = 21
let y: Int = 1000000
Int(x) * y              // 21000000

Declaration

static func *(lhs: Self, rhs: Self) -> Self
func *=(lhs: inout Self, rhs: Self) Required

Multiplies two values and stores the result in the left-hand-side variable.

Declaration

static func *=(lhs: inout Self, rhs: Self)

Default Implementations

func +(x: Self) -> Self

Returns the given number unchanged.

You can use the unary plus operator (+) to provide symmetry in your code for positive numbers when also using the unary minus operator.

let x = -21
let y = +21
// x == -21
// y == 21

Declaration

prefix public static func +(x: Self) -> Self
func +=(lhs: inout Self, rhs: Self)

Adds two values and stores the result in the left-hand-side variable.

Declaration

public static func +=(lhs: inout Self, rhs: Self)
func -=(lhs: inout Self, rhs: Self)

Subtracts the second value from the first and stores the difference in the left-hand-side variable.

Declaration

public static func -=(lhs: inout Self, rhs: Self)