Swift.Extensions var和func.哪一个更好? [英] Swift.Extensions var and func. Which one is better?

查看:103
本文介绍了Swift.Extensions var和func.哪一个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者. 这是代码

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
    }
}

我想知道abs1()函数和abs2变量之间有什么区别,它们如何工作,哪个更好?

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

推荐答案

它们的工作方式相同.这确实是一个意图的信号.我个人会推荐这种情况下的功能,这有点违反直觉,所以我会解释.

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.

第二个规则是是O(1)吗?" (这意味着运行需要一个恒定的时间,通常被认为是很短的时间."换句话说,它是否便宜"?)如果不是,则应该是一个函数.

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.

但是,第三条更微妙的规则是是否合理地将其视为实例的财产"?在这种情况下,我会说不.与实例完全不同.它是实例上的计算,而不是实例的内在 part .将其替换为非计算属性将非常荒谬(您永远不会将"4"存储为"-4"的"abs"字段).因此,我将其设为一个函数.

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.

请注意,在Swift 3中,abs是类型上的静态函数(例如,它是Double.abs(4.0)而不是(4.0).abs).那不会使您的问题无效,但是鉴于这种特定案例,这就是团队选择解决该问题的方式,我认为这是一种更好的方法.

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.

这篇关于Swift.Extensions var和func.哪一个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆