我不明白以下情况:
let a1: [[Double]] = [[1]]
let equ1 = a1 == a1 // This builds
let t1: (Double, Double) = (1, 1)
let equ2 = t1 == t1 // This builds also
let a2: [[(Double, Double)]] = [[(1,1)]]
let equ3 = a2 == a2 // This gives a build error
构建错误是
Binary operator '==' cannot be applied to two '[[(Double, Double)]]' operands
为什么我可以检查
Double
的两维数组和 2 Doubles
的元组是否相等,但不能检查该元组的两维数组?
这是预期的行为。让我们分解每个案例:
let a1: [[Double]] = [[1]]
let equ1 = a1 == a1
您正在比较 double 的二维数组,因为 Double 符合
Equaltable
协议(在本例中为 ==
)。因此,该数组也完全符合 Equaltable
协议,这使得它能够进行比较。您可能需要查看此文档。
let t1: (Double, Double) = (1, 1)
let equ2 = t1 == t1
SE-0015,Swift 2.2.1 表示您可以使用
==
函数比较最多 6 个元素的元组。
let t1: (Double, Double, Double, Double, Double, Double, Double) = (1, 1, 1, 1, 1, 1, 1)
let equ2 = t1 == t1 ❌
//Binary operator '==' cannot be applied to two '(Double, Double, Double, Double, Double, Double, Double)' operands
let a2: [[(Double, Double)]] = [[(1,1)]]
let equ3 = a2 == a2
到目前为止,元组还无法遵守任何类型的协议。即使里面的每个元素都可以这样做,但这并不意味着整个元组都可以。我发现这个PR-46668也问了和你一样的问题。
站点说明:您可能想将其包装成
Struct
或 Class
,例如:
struct DoubleModel: Comparable {
let firstElement: Double
let secondElement: Double
static func < (lhs: DoubleModel, rhs: DoubleModel) -> Bool {
lhs.firstElement == rhs.firstElement && lhs.secondElement == rhs.secondElement
}
}
let a3: [[DoubleModel]] = [[.init(firstElement: 1, secondElement: 1)]]
let equ3 = a3 == a3 ✅