Appending to an empty array giving error

▼魔方 西西 提交于 2019-12-11 12:09:34

问题


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)

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.

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?


回答1:


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)

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) }() )

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))


来源:https://stackoverflow.com/questions/25418724/appending-to-an-empty-array-giving-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!