Idiomatic way to test Swift Optionals

2019-07-13 01:16发布

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条回答
别忘想泡老子
2楼-- · 2019-07-13 01:52

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.

查看更多
登录 后发表回答