Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write an extension for the Double type that adds an absoluteValue property

Tags:

swift

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
like image 504
Chris Chen Avatar asked Jun 06 '14 05:06

Chris Chen


1 Answers

It’s just being parsed as -(4.0.absoluteValue). This works:

> (-4.0).absoluteValue
$R2: Double = 4
like image 138
zoul Avatar answered Nov 15 '22 11:11

zoul