Understanding syntax for an array of tuples in Swift

时间:2016-10-09 15:57:58

标签: arrays swift syntax tuples

I'm trying to understand syntax for arrays of tuples in Swift:

If I create a tuple:

var gameScore: (points: Int, player: String)

I can assign values like this:

gameScore = (1700, "Lisa")

And create an array of this tuple:

var gameScores = [gameScore]

I can append to the array this way:

gameScores.append((1650, "Bart"))

And this way:

gameScore = (1600, "Maggie")
gameScores += [gameScore]

But not this way:

gameScores += [(1600, "Maggie")]

Playground error is:

Playground execution failed: error: Tuples Playground.playground:38:1: error: cannot convert value of type '[(points: Int, player: String)]' to expected argument type 'inout _' gameScores += [(1600, "Maggie")]

However, this way works:

gameScores += [(points: 1600, player: "Maggie")]

Yes – I have code above that will work, but I'm trying to figure out what I'm not understanding in the failing syntax. Elements don't need to be named for the .append() method, but they need to be named for += [()].

1 个答案:

答案 0 :(得分:3)

Swift类型推理系统正在被拉伸至此处。 Swift无法在您的示例中推断出[(1600, "Maggie")]的类型。如果您提供更多信息,您的示例将编译:

gameScores += [(1600, "Maggie") as (points: Int, player: String)]

gameScores += [(1600, "Maggie")] as [(points: Int, player: String)]

gameScores = gameScores + [(1600, "Maggie")]

全部编译。

似乎Swift在涉及+=时无法推断出类型。

查看+=

的定义
func +=<C : Collection>(lhs: inout Array<C.Iterator.Element>, rhs: C)

表明lhsrhs的类型不同。 Swift无法根据给定的信息协调lhsrhs的类型。它似乎从rhs开始,然后得出结论左侧的类型为inout _,并尝试将其与gameScores的类型[(points: Int, player: String)]进行协调。它应该能够推断出类型吗?或许,但在这种情况下,由于您有一个简单的解决方法,我说给编译器一个中断并给它显式的类型信息并使其工作更容易:

gameScores += [(points: 1600, player: "Maggie")]