Swift Tutorial Swift References

Swift - copysign() Function



The Swift copysign() function returns a number with magnitude of first argument and sign of second argument.

Syntax

In Foundation framework, it is defined as follows:

public func copysign(_ __x: Double, _ __y: Double) -> Double

Parameters

x Specify a value providing the magnitude of the result.
y Specify a value providing the sign of the result.

Return Value

Returns a number with magnitude of first argument and sign of second argument.

Example:

In the example below, copysign() function returns a number with magnitude of first argument and sign of second argument.

import Foundation

print("copysign(-324.1, 4) = \(copysign(-324.1, 4))")
print("copysign(324.1, -4) = \(copysign(-324.1, -4))")
print("copysign(-500.5, -4.5) = \(copysign(-500.5, -4.5))")
print("copysign(500.5, 4.5) = \(copysign(500.5, 4.5))")

The output of the above code will be:

copysign(-324.1, 4) = 324.1
copysign(324.1, -4) = -324.1
copysign(-500.5, -4.5) = -500.5
copysign(500.5, 4.5) = 500.5

❮ Swift Math Functions