Convert positive value to negative value in swift
Asked Answered
D

2

13

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?

Derain answered 10/8, 2018 at 8:58 Comment(0)
P
16

Just use - operator.

let negativeA = -a
Phonsa answered 10/8, 2018 at 9:8 Comment(0)
K
21

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
Kuth answered 31/3, 2019 at 12:13 Comment(1)
Unfortunately with a Double, if the value is zero, you get "-0" which is odd (but valid).Snifter
P
16

Just use - operator.

let negativeA = -a
Phonsa answered 10/8, 2018 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.