Karen Martikyan Karen Martikyan - 1 year ago 81
Swift Question

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

I'm a beginner.
Here's 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's the difference between abs1() function and abs2 variable, how do they work and which one is better?

Answer Source

They are the same in how they work. It really is a signal of intent. Personally I would recommend the function in this case, which is slightly counter-intuitive, so I'll explain.

The first rule is "does it have side effects?" If so, it should be a function.

The second rule is "is it O(1)?" (That means "it takes a constant, and generally assumed to be short, period of time to run." In other words, is it "cheap?") If not, it should be a function.

But the third, more subtle rule is "is it reasonably considered a "property" of the instance?" And in this case I'd argue, no. It is a completely different thing than the instance. It is something computed on the instance, not something that is an intrinsic part of the instance. It would be fairly ridiculous for this to be replaced with a non-computed property (you'd never store "4" as the "abs" field of "-4"). So I would make it a function.

Note that in Swift 3, abs is a static function on the type (for example, it's Double.abs(4.0) rather than (4.0).abs). That doesn't invalidate your question, but given this specific case, that's how the team chose to address it, and I think it's a better way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download