问题描述
我已经创建了一个空数组存储形式(智力,双人间)的数据。我放弃了试图元组直接追加到数组中,因为它似乎SWIFT是没有设置这样做。所以,我的code的一个例子是这样的:
I have created an empty array to store data of the form (Int,Double). I gave up on trying to directly append a tuple to the array, as it seems swift is not set up to do this. So an example of my code looks like this:
var data: [(x: Int,y: Double)] = []
var newDataX: Int = 1
var newDataY: Double = 2.0
data.append(x: newDataX,y: newDataY)
有关append行的错误消息是类型'T'不符合协议IntegerLiteralConvertible,这混淆了我没有尽头。当我特地追加一个整数和一个双(即data.append(1,2.0 )),我没有收到错误消息。如果我尝试使用一个变量我得到的消息,无论哪一个变量追加的具体之一,其中之一。
The error message for the append line is "Type 'T' does not conform to protocol 'IntegerLiteralConvertible' which confuses me to no end. When I specifically append an integer and a double (ie. data.append(1,2.0)), I do not receive the error message. If I try to append one of the specifically and one of them using a variable I get the message no matter which one is the variable.
我会用+ =命令只是一个元组追加到该数组,但我明白我的方式,那就是不再beta5的一个有效的命令。是不是有什么毛病我code,我没有看到?或有另一种方式做我想做的事?
I would use the += command just append a tuple onto the array, but I the way I understand it, that is no longer a valid command in beta5. Is there something wrong with my code that I am not seeing? Or is there another way to do what I want to do?
推荐答案
的问题是, X:newDataX,Y:newDataY
不解决作为一个参数 - 而不是它通过为2个独立的参数给追加
函数,编译器查找匹配的追加
函数获取诠释
和双击
。
The problem is that x: newDataX, y: newDataY
is not resolved as a single parameter - instead it's passed as 2 separate parameters to the append
function, and the compiler looks for a matching append
function taking an Int
and a Double
.
您可以通过附加之前定义的元组解决的问题:
You can solve the problem by defining the tuple before appending:
let newData = (x: 1, y: 2.0)
data.append(newData)
或作出明确的参数对是一个元组。元组是由括号包围的列表中标识(1,2.0)
,但不幸的是这不起作用:
or making explicit that the parameters pair is a tuple. A tuple is identified by a list surrounded by parenthesis (1, 2.0)
, but unfortunately this doesn't work:
data.append( (x: 1, y: 2.0) )
如果你真的需要/想在一行追加,你可以使用一个封闭如下:
If you really need/want to append in a single line, you can use a closure as follows:
data.append( { (x: newDataX, y: newDataY) }() )
一个更优雅的解决方案是使用 typealias
:
A more elegant solution is by using a typealias
:
typealias MyTuple = (x: Int, y: Double)
var data: [MyTuple] = []
var newDataX: Int = 1
var newDataY: Double = 2.0
data.append(MyTuple(x: 1, y: 2.0))
这篇关于追加到一个空数组给错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!