在 Swift 5 中,可以用下面两种方法之一把整数转成它的绝对值。
#1. 通过 magnitude 属性取得 Int 的绝对值
Int 类型提供了 magnitude (https://developer.apple.com/documentation/swift/int/2886869-magnitude)。这个属性的声明如下。
var magnitude: UInt { get }
对于数字输入 x,x.magnitude 的值就是 x 的绝对值。
下面的例子通过 magnitude 属性取得 Int 实例的绝对值。
let input = -4
print(input.magnitude) // prints: 4
#2. 通过 abs(_:) 方法取得 Int 的绝对值
Swift 有一个名为 abs(_:) (https://developer.apple.com/documentation/swift/2885649-abs) 的全局数字函数。它的方法声明如下。
func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
返回所给数字的绝对值。
下面的例子调用全局 abs(_:) 函数取得 Int 实例的绝对值。
let input = -4
print(abs(input)) // prints: 4
从英语翻译·查看原文In Swift 5, either of the following two approaches lets you turn an integer into its absolute value.
#1. Obtain an Int's absolute value through its magnitude property
The Int type provides magnitude (https://developer.apple.com/documentation/swift/int/2886869-magnitude). This property is declared like this:
var magnitude: UInt { get }
For a numeric input x, the value x.magnitude gives x's absolute value.
Here is an example using the magnitude property to retrieve the absolute value from an instance of Int:
let input = -4
print(input.magnitude) // prints: 4
#2. Obtain an Int's absolute value through the abs(_:) method
A global numeric function in Swift is named abs(_:) (https://developer.apple.com/documentation/swift/2885649-abs). Its method declaration is:
func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
Gives the supplied number's absolute value.
Here is an example calling the global abs(_:) function to retrieve the absolute value from an instance of Int:
let input = -4
print(abs(input)) // prints: 4