В Swift 5 любой из следующих двух способов позволяет получить абсолютное значение целого числа.
#1. Получение абсолютного значения Int через свойство magnitude
Тип 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. Получение абсолютного значения Int через метод abs(_:)
В 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