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?
You can write int myNum *= -1; It will change your num to negative.
The Anti-Lock braking system has two key functions. Foremost, is to stop the wheels from locking up when immediate brakes are applied and secondly to prevent the car from skidding on slippery roads. Furthermore, Swift's ABS has been accompanied by electronic brake force distribution system and brake assist.
Swift 5 solution Try using value < 0. This will check if the value is less than 0.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With