这个问题有点“讨论”性质,但我会补充两点,以支持有时更喜欢元组而不是结构。
有限大小元组的原生 Equatable 一致性
在 Swift 2.2 中,最大大小为 6 的元组本身是可等价的,因为它的成员是可等价的
这意味着元组有时会成为在有限范围内使用较小构造的自然选择。
例如考虑下面的例子,使用(1): a structure
struct Foo {
var a : Int = 1
var b : Double = 2.0
var c : String = "3"
}
var a = Foo()
var b = Foo()
// a == b // error, Foo not Equatable
/* we can naturally fix this by conforming Foo to Equatable,
but this needs a custom fix and is not as versatile as just
using a tuple instead. For some situations, the latter will
suffice, and is to prefer. */
func == (lhs: Foo, rhs: Foo) -> Bool {
return lhs.a == rhs.a && lhs.b == rhs.b && lhs.c == rhs.c
}
和(2):一个元组
/* This will be native in Swift 2.2 */
@warn_unused_result
public func == <A: Equatable, B: Equatable, C: Equatable>(lhs: (A,B,C), rhs: (A,B,C)) -> Bool {
return lhs.0 == rhs.0 && lhs.1 == rhs.1 && lhs.2 == rhs.2
}
/* end of native part ... */
var aa = (1, 2.0, "3")
var bb = (1, 2.0, "3")
aa == bb // true
aa.0 = 2
aa == bb // false
对不同类型元组的通用访问:比不同类型结构更通用
从上面(比较== 函数)可以看出,元组很容易在泛型上下文中使用,因为我们可以使用.0、.1 访问它们的匿名成员属性...后缀;而对于结构体,模仿这种行为的最简单方法很快就会变得相当复杂,需要运行时自省等工具,请参阅e.g. this。