Swift, Equatable 协议错误? [英] Swift, Equatable protocol bug?
本文介绍了Swift, Equatable 协议错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 Swift 中构建一个非常简单的结构,其中包含一个可选值数组.此结构必须符合 Equatable 协议.这是代码:
I am building a very simple structure in Swift that contains an array of optional values. This struct must conform to the Equatable protocol. This is the code:
struct MyTable: Equatable {
var values: [Int?] = Array(count: 64, repeatedValue: nil)
}
func == (lhs: MyTable, rhs: MyTable) -> Bool {
return lhs.values == rhs.values
}
很简单.我没有看到任何错误,但编译器给出了错误:'[Int?]' 不能转换为 'MyTable'".我在做蠢事吗?或者这是编译器的错误?谢谢!
Quite simple. I see no mistakes, but the compiler gives error: "'[Int?]' is not convertible to 'MyTable'". Am I doing something stupid? or is this a compiler's bug? Thanks!
(使用 Xcode6-Beta5)
(Using Xcode6-Beta5)
推荐答案
不工作的原因是没有为具有可选元素的数组定义==
运算符,仅用于非可选元素元素:
The reason why it does not work is there is no ==
operator defined for arrays with optional elements, only for non-optional elements:
/// Returns true if these arrays contain the same elements.
func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool
您可以提供自己的:
func ==<T : Equatable>(lhs: [T?], rhs: [T?]) -> Bool {
if lhs.count != rhs.count {
return false
}
for index in 0..<lhs.count {
if lhs[index] != rhs[index] {
return false
}
}
return true
}
这篇关于Swift, Equatable 协议错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文