Swift 5에서는 아래 두 방법 중 하나로 정수를 절댓값으로 바꿀 수 있습니다.
#1. magnitude 속성으로 Int의 절댓값 얻기
Int 타입에는 magnitude(https://developer.apple.com/documentation/swift/int/2886869-magnitude)가 있습니다. 이 속성의 선언은 이렇습니다:
var magnitude: UInt { get }
숫자 입력 x에 대해 x.magnitude 값은 x의 절댓값입니다.
Int 인스턴스에서 magnitude 속성으로 절댓값을 얻는 예제입니다:
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
전달한 숫자의 절댓값을 반환합니다.
Int 인스턴스에서 전역 abs(_:) 함수로 절댓값을 얻는 예제입니다:
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