はじめに
絶対値を取得したい時があったので、調べるとabsを使えばできるようなのでやってみました。
実装
import Foundation
let intPlus: Int = 10
let intMinus: Int = -10
let doublePlus: Double = 10.5
let doubleMinus: Double = -10.5
let floatPlus: Float = 10.5
let floatMinus: Float = -10.5
let cgFloatPlus: CGFloat = 10.5
let cgFloatMinus: CGFloat = -10.5
print(abs(intPlus)) // 10
print(abs(intMinus)) // 10
print(abs(doublePlus)) // 10.5
print(abs(doubleMinus)) // 10.5
print(abs(floatPlus)) // 10.5
print(abs(floatMinus)) // 10.5
print(abs(cgFloatPlus)) // 10.5
print(abs(cgFloatMinus)) // 10.5
ドキュメントコメント
/// Returns the absolute value of the given number.
///
/// The absolute value of `x` must be representable in the same type. In
/// particular, the absolute value of a signed, fixed-width integer type's
/// minimum cannot be represented.
///
/// let x = Int8.min
/// // x == -128
/// let y = abs(x)
/// // Overflow error
///
/// - Parameter x: A signed number.
/// - Returns: The absolute value of `x`.
@inlinable public func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
おわり
参考にした記事ではfabs
やfabsf
などを使っていましたが、全てabs
でいけました
参考記事