我知道,例如,Swift的元组用作函数返回多个值的简单方法。但是,除了这种“简单性”之外,我认为使用元组代替结构没有必要。
因此,我的问题是:在设计方面,是否有任何一种情况显然是元组比结构更好的选择?
最佳答案
这个问题有点“讨论”性质,但我要补充两点,即有时倾向于使用元组而不是结构。
有限元组的本地Equatable一致性
在Swift 2.2中,由于成员是平等的,大小最大为6的元组在本地是平等的
这意味着在有限范围内使用元组有时会成为元组的自然选择。
例如。考虑下面的示例,使用
(1)
:一个结构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
...后缀访问它们的匿名成员属性;而对于结构而言,快速模仿此行为的最简单方法变得相当复杂,需要诸如运行时自省(introspection)之类的工具,请参见e.g. this。