I want to convert a positive value to a negative value, for example:
let a: Int = 10
turn it to -10
, my current idea is just use it to multiple -1
a * -1
I'm not sure if this is proper, any idea?
I want to convert a positive value to a negative value, for example:
let a: Int = 10
turn it to -10
, my current idea is just use it to multiple -1
a * -1
I'm not sure if this is proper, any idea?
With Swift 5, according to your needs, you can use one of the two following ways in order to convert an integer into its additive inverse.
negate()
methodInt
has a negate()
method. negate()
has the following declaration:
mutating func negate()
Replaces this value with its additive inverse.
The Playground code samples below show how to use negate()
in order to mutate an integer and replace its value with its additive inverse:
var a = 10
a.negate()
print(a) // prints: -10
var a = -10
a.negate()
print(a) // prints: 10
Note that negate()
is also available for all types that conform to SignedNumeric
protocol.
-
)The sign of a numeric value can be toggled using a prefixed -
, known as the unary minus operator. The Playground code samples below show how to use it:
let a = 10
let b = -a
print(b) // prints: -10
let a = -10
let b = -a
print(b) // prints: 10
© 2022 - 2024 — McMap. All rights reserved.