测试Swift Optionals的惯用方式 [英] Idiomatic way to test Swift Optionals

查看:98
本文介绍了测试Swift Optionals的惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是在问这些扩展名是否是一个好主意,这只是一个思想实验,我正在尝试从实践中学习.

与克里斯蒂安·拉特纳(Christian Lattner)达成共识,通常认为这种方法是更可取的,我认为我会表达自己:

Agreeing with Christian Lattner, that methods are generally preferable, I thought I'd play with being able to express:

someVariable.isNil

someVariable.notNil

实施该程序后,我发现自己对以下一种或另一种实施方式是否比另一种实施方式感到好奇,这是出于什么原因?一个会比其他的更有效率.是否会有一种边沿情况是另一种更好的方法.

Implementing it, I found myself curious if one or the other of the following implementations was preferable to the other, and for what reasons? Would one be more efficient than the others. Would there be edge cases that are better one way or the other.

解决方案1:

extension Optional {
    var isNil:Bool {
        switch self {
        case .None:
            return true
        case .Some:
            return false
        }
    }

    var notNil:Bool {
        switch self {
        case .None:
            return false
        case .Some:
            return true
        }
    }
}

解决方案2:

extension Optional {
    var isNil:Bool {
        return self == nil
    }

    var notNil:Bool {
        return self != nil
    }
}

推荐答案

我不确定这些方法是否有用,但是它们为讨论提供了良好的起点.

I'm not sure how useful these methods are, but they make a fine starting point for discussion.

看看Optional的当前实现:

Take a look at the current implementation of Optional:

https://github.com/apple/swift/blob/ecd3c07a86394aa6b1372f1370f470842b39ea6e/stdlib/public/core/Optional.swift

在顶部附近,您可以看到它自己的最原始表示形式使用.None和.Some.因此,解决方案1 ​​是最直接的方法,开销最小,并且遵循Optional自身实现中使用的模式.我认为这是惯用的.

Near the top, you can see that its own most primitive representation uses .None and .Some. So Solution 1 is the most direct approach, has the least overhead, and follows the pattern used in the implementation of Optional itself. I'd say that counts as idiomatic.

使用operator ==只会添加不必要的间接访问,甚至无法按照您呈现的方式进行操作.

Using operator == just adds unnecessary indirection and wouldn't even work the way you presented it.

这篇关于测试Swift Optionals的惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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