Swift - Convertir a valor absoluto
¿Hay alguna manera de obtener un valor absoluto de un entero?
por ejemplo
-8
to
8
Ya intenté usar UInt() asumiendo que convertirá el valor Int a unsigned pero no funcionó.
3 answers
La función estándar abs
funciona muy bien aquí
var c = -8
println(abs(c))
// 8
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 18:39:43
De acuerdo con sus necesidades, con Swift 4, puede usar una de las dos formas siguientes para resolver su problema (funciona también para otras variables numéricas, como CGFloat, Double, etc.):
#1. Obtenga el valor absoluto de un Int
de la propiedad magnitude
Con Swift 4, Int
tiene un magnitude
propiedad. magnitude
tiene la siguiente declaración:
var magnitude: UInt { get }
Para cualquier valor numérico
x
,x.magnitude
es el valor absoluto dex
.
El el siguiente fragmento de código muestra cómo usar la propiedad magnitude
para obtener el valor absoluto en una instancia Int
:
let value = -5
print(value.magnitude) // prints: 5
#2. Obtenga el valor absoluto de un Int
del método abs(_:)
Swift 4 tiene una función numérica global llamada abs(_:)
método. abs(_:)
tiene la siguiente declaración:
func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
Devuelve el valor absoluto del número dado.
El siguiente fragmento de código muestra cómo usar la función global abs(_:)
para obtener el valor absoluto en una instancia Int
:
let value = -5
print(abs(value)) // prints: 5
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-16 11:41:12
Si desea obtener un valor absoluto de un double o Int, use fabs
func:
var c = -12.09
print(fabs(c)) // 12.09
c = -6
print(fabs(c)) // 6
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 05:32:22