Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert positive value to negative value in swift

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?

like image 419
William Hu Avatar asked Aug 10 '18 08:08

William Hu


People also ask

How do you make a number negative in Swift?

You can write int myNum *= -1; It will change your num to negative.

What is abs function in swift?

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.

How do you know if a number is negative in Swift?

Swift 5 solution Try using value < 0. This will check if the value is less than 0.


1 Answers

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.


#1. Using negate() method

Int 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.


#2. Using the unary minus operator (-)

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
like image 67
Imanou Petit Avatar answered Sep 20 '22 21:09

Imanou Petit