本文介绍了为什么未为可选数组定义Equatable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我一个为什么它不起作用的充分理由:

Can someone give me a good reason for why this doesn't work:

let a: [Int]? = [1]
let b: [Int]? = nil
a == b

这将是我建议的(如果不够优雅)的解决方案.但这是微不足道的,所以我觉得我很想知道为什么未实现这一点的充分理由.

This would be my proposed (if inelegant) solution. But it's trivial, so I feel like I'm missing a good reason why this isn't implemented.

func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool {

    if let lhs = lhs, let rhs = rhs {
        return lhs == rhs
    }
    else if let _ = lhs {
        return false
    }
    else if let _ = rhs {
        return false
    }

    return true
}

推荐答案

更新:条件一致性已在 Swift 4.1中实现. Equatable元素的数组和可选元素自己Equatable现在,以及您的代码

Update: Conditional conformance has been implemented in Swift 4.1. Arrays and optionals of Equatable elements are themselves Equatable now, and your code

let a: [Int]? = [1]
let b: [Int]? = nil
a == b

编译并按预期在Xcode 9.3中工作.解决方法不是不再需要了.

compiles and works as expected in Xcode 9.3. The workarounds are notneeded anymore.

(旧答案:)仅当基础包装类型是可等于的时,才可以比较可选选项:

(Old answer:)Optionals can be compared only if the underlying wrapped type is equatable:

public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

如果元素类型是相等的,则现在可以比较:

Now Arrays can be compared if the element type is equatable:

/// Returns true if these arrays contain the same elements.
public func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool

,但是即使对于等于类型的TArray<T> 也不符合 .

but even for equatable types T, Array<T> does not conform to the Equatable protocol.

目前,这在Swift中是不可能的,例如参见为什么我不能使Array符合Equatable?进行讨论在Apple开发者论坛中.这项变更随着执行 SE-0143条件符合在Swift 4中.

At present, this is not possible in Swift, see for exampleWhy can't I make Array conform to Equatable? for a discussionin the Apple developer forum. This change with the implementationof SE-0143 Conditional conformancesin Swift 4.

您的实现看起来正确,这可能是一个不同的实现使用带有模式匹配的开关/盒:

Your implementation looks correct, here is a possible different oneusing switch/case with pattern matching:

func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool {

    switch (lhs, rhs) {
    case let (l?, r?) : // shortcut for (.Some(l), .Some(r))
        return l == r
    case (.None, .None):
        return true
    default:
        return false
    }
}

这篇关于为什么未为可选数组定义Equatable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 10:12