0
0

【Swift】負の数でも、数字の部分だけ取得したい(絶対値)

Last updated at Posted at 2024-02-06

はじめに

絶対値を取得したい時があったので、調べると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

おわり

参考にした記事ではfabsfabsfなどを使っていましたが、全てabsでいけました

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0