Idiomatic way to test Swift Optionals

只愿长相守 提交于 2019-12-13 16:23:40

问题


I'm NOT asking if these extensions are a good idea or not, it's just a thought experiment, I'm trying to learn from the practice.

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

someVariable.isNil

and

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.

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

Solution 2:

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

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

回答1:


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

Take a look at the current implementation of Optional:

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

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.

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



来源:https://stackoverflow.com/questions/34360374/idiomatic-way-to-test-swift-optionals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!