16. How to use Numeric or BinaryInteger protocol?

It will take about 2 minutes to finish reading this article.

1. Numeric

If you want to represent a function whose parameter type can be any kind of number, including both integers and floating-point numbers, you can use the protocol Numeric for the generic type. Here’s how you can represent it:

1
2
3
4
5
6
7
func processInteger<T: BinaryInteger>(_ number: T) {
// handle integers here
print("The integer is: \(number)")
}

processInteger(5) // integer parameter

2. BinaryInteger

BinaryInteger is a protocol in Swift that is used to represent integer types. It defines the basic behaviors and functionalities of integers. To make a function capable of accepting parameters that conform to the BinaryInteger protocol, you can do so as follows:

1
2
3
4
5
6
func processInteger<T: BinaryInteger>(_ number: T) {
// Process the integer here
print("The integer is: \(number)")
}

processInteger(5) // Integer argument

By using T: BinaryInteger within the function, you ensure that the function accepts any integer type that adheres to the BinaryInteger protocol, including Int, Int8, Int16, Int32, Int64, UInt, UInt8, UInt16, UInt32, and UInt64, among others.