Numeric

protocol Numeric

Declares methods backing binary arithmetic operators--such as +, - and *--and their mutating counterparts.

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 declares a method that calculates the total of any sequence with Numeric elements.

extension Sequence where Element: Numeric {
    func sum() -> Element {
        return reduce(0, +)
    }
}

The sum() method is now available on any sequence or collection with numeric values, whether it is an array of Double or a countable range of Int.

let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum()
// arraySum == 16.5

let rangeSum = (1..<10).sum()
// rangeSum == 45

Conforming to the Numeric Protocol

To add Numeric protocol conformance to your own custom type, implement the required mutating methods. Extensions to Numeric provide default implementations for the protocol's nonmutating methods based on the mutating variants.

Inheritance Equatable, ExpressibleByIntegerLiteral View Protocol Hierarchy →
Associated Types
Magnitude : Comparable, Numeric

A type that can represent the absolute value of any possible value of the conforming type.

IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral

A type that represents an integer literal.

The standard library integer and floating-point types are all valid types for IntegerLiteralType.

Import import Swift

Initializers

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

source: A value to convert to this type.

Declaration

init?<T>(exactly source: T)
init(integerLiteral:)

Creates an instance initialized to the specified integer value.

Do not call this initializer directly. Instead, initialize a variable or constant using an integer literal. For example:

let x = 23

In this example, the assignment to the x constant calls this integer literal initializer behind the scenes.

value: The value to create.

Declaration

init(integerLiteral value: Self.IntegerLiteralType)

Declared In

ExpressibleByIntegerLiteral

Instance Variables

var magnitude: Self.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 { get }

Instance Methods

func *(_:rhs:) 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

Parameters: lhs: The first value to multiply. rhs: The second value to multiply.

Declaration

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

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

Parameters: lhs: The first value to multiply. rhs: The second value to multiply.

Declaration

func *=(lhs: inout Self, rhs: Self)
func +(_:rhs:) Required

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.

let x: Int8 = 21
let y: Int = 1000000
Int(x) + y              // 1000021

Parameters: lhs: The first value to add. rhs: The second value to add.

Declaration

func +(lhs: Self, rhs: Self) -> Self
func +=(_:rhs:) Required

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

Parameters: lhs: The first value to add. rhs: The second value to add.

Declaration

func +=(lhs: inout Self, rhs: Self)
func ==(_:rhs:) Required

Returns a Boolean value indicating whether two values are equal.

Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func ==(lhs: Self, rhs: Self) -> Bool

Declared In

Equatable
func -(_:rhs:) Required

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.

let x: UInt8 = 21
let y: UInt = 1000000
y - UInt(x)             // 999979

Parameters: lhs: A numeric value. rhs: The value to subtract from lhs.

Declaration

func -(lhs: Self, rhs: Self) -> Self
func -=(_:rhs:) Required

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

Parameters: lhs: A numeric value. rhs: The value to subtract from lhs.

Declaration

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

Default Implementations

init(integerLiteral:)

Creates an instance initialized to the specified integer value.

Do not call this initializer directly. Instead, initialize a variable or constant using an integer literal. For example:

let x = 23

In this example, the assignment to the x constant calls this integer literal initializer behind the scenes.

value: The value to create.

Declaration

init(integerLiteral value: Self)

Declared In

ExpressibleByIntegerLiteral
func !=(_:rhs:)

Returns a Boolean value indicating whether two values are not equal.

Inequality is the inverse of equality. For any values a and b, a != b implies that a == b is false.

This is the default implementation of the not-equal-to operator (!=) for any type that conforms to Equatable.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func !=(lhs: Self, rhs: Self) -> Bool

Declared In

Equatable
prefix func +(_:)

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

Returns: The given argument without any changes.

Declaration

prefix func +(x: Self) -> Self