我知道 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 .
关于swift - Swift 中的元组与结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153873/