Swift.Extensions var and func. Which one is better?

I'm a newbie. Here is the code

extension Double  {
    func abs1() -> Double  {
        return ( self > 0 ) ? self : -1.0 * self
    }

    var abs2 : Double {
        return ( self > 0 ) ? self : -1.0 * self
    }
}

I would like to know what is the difference between the abs1 () function and the abs2 variable, how they work and which one is better?

+4
source share
1 answer

They are the same in how they work. This is really a signal of intent. Personally, I would recommend a function in this case, which is a little contrary to intuition, so I will explain.

First rule: "are there any side effects?" If so, it should be a function.

: " O (1)?" ( , " ". , "?" ). , .

, - " " "?" , . , . , , -, . , ( "4" "abs" "-4" ). .

, Swift 3 abs (, Double.abs(4.0) (4.0).abs). , , , , .

+5

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


All Articles