Swift 中的元组与结构 [英] Tuple vs Struct in Swift
问题描述
例如,我理解 Swift 的元组作为函数返回多个值的一种简单方法.然而,除了这种简单性"之外,我不太清楚使用元组而不是结构体的必要性.
I understand that Swift's tuples serve, for example, as a simple way for a function to return multiple values. However, beyond this "simplicity aspect", I don't see very well any necessity of using tuples instead of structs.
因此,我的问题是:在设计方面,是否存在元组显然比结构更好的选择的情况?
Therefore, my question: in terms of design, is there any scenario where tuples are clearly a better choice than structs?
推荐答案
这个问题有点讨论"性质,但我会补充两点,支持有时更喜欢元组而不是结构.
This question of a slightly "discussion" nature, but I'll add two points in favour of sometimes preferring tuples over structures.
有限大小元组的原生 Equatable 一致性
在 Swift 2.2 中,最大大小为 6 的元组将是本地可相等的,因为它的成员是可相等的
In Swift 2.2, tuples of up to size 6 will be natively equatable, given that it's members are equatable
这意味着元组有时会成为在有限范围内使用较小结构的自然选择.
This means tuples will sometimes be the natural choice over using smaller constructs in a limited scope.
例如考虑以下示例,使用 (1)
: a structure
E.g. consider the following example, using (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
... 后缀;而对于结构体,模仿这种行为的最简单方法很快就会变得非常复杂,需要诸如运行时自省等工具,请参阅 eg这个.
From the above (compare the ==
functions) it's also apparent that tuples are easily to work with in the context of generics, as we can access their anonymous member properties using the .0
, .1
... suffixes; whereas for a struct, the easiest way to mimic this behaviour quickly becomes quite complex, needing tools such as runtime introspection and so on, see e.g. this.
这篇关于Swift 中的元组与结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!