Write an extension for type Double that adds the absoluteValue property

Does anyone know why the last line outputs -4.0 instead of 4.0?

extension Double {
    var absoluteValue: Double {
    if self > 0.0 {
        return self
    }
    else {
        return -1 * self
        }
    }
}

var minusTwo = -2.0
minusTwo.absoluteValue  // 2.0

let minusThree = -3.0
minusThree.absoluteValue    // 3.0

-4.0.absoluteValue  // -4.0
+4
source share
4 answers

It is simply analyzed as -(4.0.absoluteValue). It works:

> (-4.0).absoluteValue
$R2: Double = 4
+9
source

The reason is because you missed the subtle priority of the expression operator.

In your expression:

-4.0.absoluteValue

There are two operators: - (Unary minus operator, prefix) and. (method operator). And that seems to be a priority. overloaded - and the expression was analyzed for:

-(4.0.absoluteValue)

Therefore, you get the result 4.0 absolute value, then turned it over with the unary minus operator and got -4.0.

Swift , . ( ) . . , , .

, . , - , + - */=, .

Btw, . absoluteValue, , .

extension Double {
    func absoluteValue() -> Double {
        if self < 0 {
            return -self
        } else {
            return self
        }
    }
}

let myDouble: Double = -7.65
println("The absolute value of \(myDouble) is \(myDouble.absoluteValue()).")
+3

Tested with Swift 4.0.2:

extension Double {
    var absoluteValue: Double {
        return abs(self)
    }
}

var x = -75.34
print(x.absoluteValue) // Prints 75.34
print((-31.337).absoluteValue) // Prints 31.337
+1
source

Here is my solution:

extension Double{
    // Abs property
    var absoluteValue: Double{
        return Double.abs(self)
    }
    // Abs method
    func absValFunc() ->Double{
        return Double.abs(self)
    } }

var doubleValue = -36.00 
doubleValue.absoluteValue 
doubleValue.absValFunc()
0
source

Source: https://habr.com/ru/post/1543501/


All Articles